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

- core/drupal
- core/jquery
- core/drupalSettings

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

  • 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.
    – apaderno
    Commented May 24, 2023 at 7:53
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
    – Community Bot
    Commented May 24, 2023 at 22:49

1 Answer 1


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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.