n Passing data from PHP to javascript in Drupal 8 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

in this article, I'll show you how to pass data from PHP to javascript in Drupal 8.


first create your librarie as in example below :

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


use $variables['#attached']['drupalSettings'] to pass variable to javascript like the below example :


 * @param $variables
function mymodule_preprocess_page(&$variables)
  $color_body = 'red';
  //Add a JS library
  $variables['#attached']['library'][] = 'mymodule/mymodule-js';
  // pass variable to Drupal.Settings
  $variables['#attached']['drupalSettings']['mymodule']['color_body'] = $color_body;


We can access this data in javascript by drupalSettings:

(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.MyModuleBehavior = {
    attach: function (context, settings) {
      // get color_body value with "drupalSettings.mymodule.color_body"
      var color_body = drupalSettings.mymodule.color_body;
      $('body').css('background', color_body);
})(jQuery, Drupal, drupalSettings);

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts


Page Facebook