Passing data from PHP to javascript variable available to all pages in Drupal 8

Most of us pass data from PHP to javascript variable available to all pages in Drupal 7 is by:

  
/**
 * Implements hook_init()
 */
function mymodule_init() {
  $computed_data = mymodule_get_data();
  drupal_add_js(array('mymodule_computed_data' => $computed_data), 'setting');
}
  

We can access this data in javascript by:

Setup Drupal 8 module using Composer

Drupal uses an externally-maintained repository the https://packagist.drupal-composer.org but this repo is scheduled to be deprecated in January 2017 by then we will be using https://packages.drupal.org/8 repo URL.

It is assumed that composer is already installed in your system. Make sure your composer version is 1.0.0 or higher, to check execute:

  
composer -V
  

If it is lower than version 1.0.0, update it by:

  
composer self-update
  

Change directory to your Drupal root path.

Installing ip2location-php required library for Smart IP's data source IP2Location binary database

Using Smart IP's data source IP2Location binary database requires ip2location/ip2location-php library which contains API that reads its database file. This article will show how to setup this API using composer.

The following procedures are tested on my Linode server running Centos 7 64-bit Linux distribution.

  1. First we will install composer: