-2

I have an array define in my module and I want to pass that array value to js file according to that i want to add class to html. .module file

$aha_initiatives = '#aha_initiatives';
  //Add a JS library
  $variables['#attached']['library'][] = 'benefit_with_unite_tabs/quick-tab';
$variables['#attached']['drupalSettings']['lotus']['lotusJS']['aha_initiatives'] = $aha_initiatives;

.js file

(function ($, Drupal, drupalSettings) {

Drupal.behaviors.benefit_with_unite_tabls = {
  attach: function (context, settings) {
    // can access setting from 'drupalSettings';
    var aha_initiatives = drupalSettings.lotus.lotusJS.aha_initiatives;

     if(window.location.hash == aha_initiatives) {
        $(".tabbable #myTab ."+window.location.hash.substr(1)).addClass("active");
        $(".tabbable #myTabContent #"+window.location.hash.substr(1)).addClass("active in");
      }
  }
};
})(jQuery, Drupal, drupalSettings);

here iam sending single variable but i want to send array how can I do that

  • 1
    An array is a single variable - pass it as you would any other, it’ll be available in your js – Clive Jan 31 '18 at 19:08
1

  // In your form alter or block or controller or where ever you have this attached.
$array = [
  'red' => 'red so hot right now',
  'blue' => 'wow thats blue',
];
$form['#attached']['drupalSettings']['myArrayOfStuff'] = $array;
   

Then JS:

console.log(drupalSettings.myArrayOfStuff);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.