Information for: DEVELOPERS   PARTNERS

Add a custom variable to Drupal.Settings

Fast Track to Drupal 8 Coding – Back to intro
Previous lesson – Previous lesson

Lesson Goal

Passing configuration values from PHP to a JavaScript library.

In Drupal, you can pass values to your JavaScript using the Drupal Settings class. The name of the class and how you pass the settings in Drupal 8 have changed some from Drupal 7.

The following items are new in Drupal 8:

  • A different class in JavaScript (drupalSettings)
  • You must declare a dependency to core/drupalSettings in your library definition.
Drupal Version Method  
Drupal 7 Use drupal\_add\_js() or #attached Use Drupal.settings in JavaScript
Drupal 8 Declare a dependency on drupalSettings Use drupalSettings in JavaScript

Drupal 7 method

In the lotus.module file:

function lotus_preprocess_html(&$variables) {
  $lotus_height = '300px';
  //Add a JS library
  drupal_add_js(drupal_get_path('module', 'lotus') . '/js/lotus.js');
  drupal_add_js(array('lotus' => array('lotus_height' => $lotus_height)), 'setting');
}

In the lotus.js file:

(function ($, Drupal) {
Drupal.behaviors.LotusBehavior = {
  attach: function (context, settings) {
    // can access setting from 'settings' or 'Drupal.settings';
    var lotusHeight = Drupal.settings.lotus.lotus_height;
    $('lotusElement').css('height', lotusHeight);
  }
};
})(jQuery, Drupal);

Drupal 8 method

In the lotus.libraries.yml file, you must declare a dependency to drupalSettings:

lotus-js:
  version: 1.x
  js:
    js/lotus.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

In the lotus.module file:

function lotus_preprocess_html(&$variables) {
  $lotus_height = '300px';
  //Add a JS library
  $variables['#attached']['library'][] = 'lotus/lotus-js';
$variables['#attached']['drupalSettings']['lotus']['lotusJS']['lotus_height'] = $lotus_height;
}

In the lotus.js file:

(function ($, Drupal, drupalSettings) {
Drupal.behaviors.LotusBehavior = {
  attach: function (context, settings) {
    // can access setting from 'drupalSettings';
    var lotusHeight = drupalSettings.lotus.lotusJS.lotus_height;
    $('lotusElement').css('height', lotusHeight);
  }
};
})(jQuery, Drupal, drupalSettings);