Drupal Answers Asked by Sl4rtib4rtf4st on October 26, 2021
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);
}
}());
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));
Answered by Sl4rtib4rtf4st on October 26, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP