Score:0

How can I add drupalSettings values with the #attached array?

fo flag

In D7, we have used drupal_add_js with DrupalSettings for accessing php variables to javascript files, for that we have used in D7 in my custom function like below

function custom_function($data)
{
   drupal_add_js(array('test_ajax_responders' => $data), 'setting');
}

But for D9, we need to use #attached property to replace this, but how i need to pass this $data related in to $attachments. Seems this is my custom_function and $data is populating dynamically, so hard coding with page_attachments is not a feasible and that is used for different logic

So for this custom point of view how we can attach the drupalSetting variables in to existing $attachements array to get in javascript files. I have tried below possibilities in D9 and nothing worked out.

function custom_function($data)
{
    return ['#attached' => ['drupalSettings' => [ 'test_ajax_responders' => $data, ],], ];
}

function custom_function($data) {
    $page['#attached']['drupalSettings']['test_ajax_responders'] = $data;
    \Drupal::moduleHandler()->alter('page_attachments', $page);
}



libraries.yml file example

dependencies:        
- core/drupal
- core/jquery
- core/drupalSettings

Please help me to get my $data custom variable in to javascript files by using the above way.

apaderno avatar
us flag
Welcome to Drupal Answers! Without knowing which hook/function/method is calling `custom_function()` we cannot tell you what the correct code should be and what `custom_function()` should return.
Score:0
cn flag

This depends on how dynamic the data is. Where do you get it from? Ideally you put it there. For example, attach the js data of a node in a preprocess hook. See https://drupal.stackexchange.com/a/288989/47547

If this is not possible attach it to $attachments['#attached'] via hook_page_attachments() and declare the dynamic cache metadata in $attachments['#cache']. However, this makes the page less cacheable. Depending on how dynamic the data is, consider loading it lazily via Ajax when the client is already running Ajax like in your case.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.