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
Category:

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

mymodule.libraries.yml

first create your librarie as in example below :

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

mymodule.module

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

<?php


/**
 * @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;
}

js/mymodule.js

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);
Tags :

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon