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
1 Asked on November 28, 2021
1 Asked on November 25, 2021 by srodrig
1 Asked on November 25, 2021
2 Asked on November 23, 2021 by sandesh-yadav
5 Asked on November 23, 2021 by arbee
1 Asked on November 19, 2021 by lee-woodman
1 Asked on November 19, 2021 by blueztechz
Get help from others!
Recent Answers
Recent Questions
© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP