1

I add a variable in the backend to a render array like so (removed superfluous code):

$some_var = 'Hello World';
return [
  '#attached' => [
    'drupalSettings' => ['someVar' => $some_var],
  ],
  '#theme' => 'core_portal_customer_subscription_edit',
  '#data' => [
    'namespace_something' => $some_var,
  ]
];

I would then like to use that variable in my JavaScript but I can't seem to access the drupalSettings.

I tried doing the following but that console.logs undefined.

(function($, Druapl, drupalSettings) {
  Drupal.behaviors.escrowPortalCore = {
    ...
    console.log(druaplSettings.someVar);
  }
}());
0

When you need to use a variable in the JavaScript you have set from the backend and added to the drupalSettings, you can access that variable using the drupalSettings object like tried in the example code from the question but then without adding drupalSettings to the js function, like so:

(function($, Drupal, drupalSettings) {
  Drupal.behaviors.portalCore = {
    ...
    console.log(druaplSettings.someVar); // "Hello World"
  }
}(jQuery, Drupal, drupalSettings));
3
  • 1
    That isn’t right - your anonymous function isn’t being passed the required parameters – Clive Jul 14 '20 at 15:44
  • @Clive I found out what you mean, weird that it still works when omitting those parameters – Sl4rtib4rtf4st Jul 15 '20 at 7:14
  • Probablement because drupalSettings is defined in the global space. You can access it directly from the console. The variable is explicitely defined as window.drupalSettings = JSON.parse(settingsElement.textContent); in drupalSettingsLoader.js. Also, there is a typo in your code : console.log(druaplSettings.someVar) – Simon Vart Jul 21 '20 at 12:42

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.