AnswerBun.com

When passing a variable from a render array to JavaScript how do you reach that variable in your Javascript

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);
  }
}());

One Answer

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

Add your own answers!

Related Questions

Social Media Embed Problems With the URL Embed module

0  Asked on November 30, 2021 by mckinzie25

 

Contextual links for node blocks

3  Asked on November 28, 2021

   

Set node to flagged by default

1  Asked on November 28, 2021 by andrew-morris

     

How do I replace drush_set_error()?

1  Asked on November 28, 2021

   

Get file ID and path to use in View template

1  Asked on November 25, 2021 by srodrig

         

How to use drupal_add_library with a module?

2  Asked on November 25, 2021

   

Ajax Form Not Working in some Some Regions

2  Asked on November 23, 2021 by sandesh-yadav

     

Facebook Album fetcher

1  Asked on November 23, 2021 by rajat-goyal

 

Condition on current moderation state

2  Asked on November 23, 2021 by paul-cappucci

   

how to apply a css code for a specific screen size

1  Asked on November 23, 2021 by coding-mv

 

hook_entity_predelete never called

0  Asked on November 23, 2021

   

User reference and Views 3 and Panels 3

1  Asked on November 21, 2021

     

MetaTag with JSON API won’t serialize

2  Asked on November 21, 2021 by johnventions

   

How to disable Rich Text Editor in image field caption ?

1  Asked on November 19, 2021 by lee-woodman

   

search block form not accepting special characters in drupal 7

1  Asked on November 19, 2021 by blueztechz

   

Unknown engine type outputformat

1  Asked on November 19, 2021 by gilles9999

     

Ask a Question

Get help from others!

© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP