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.