We have a paragraph field (field_pr_custom
) on the Basic
page content type that has a custom twig template, pr-custom.html.twig
. In the twig template, we need to pass in an array inside of a <script>
tag. To accomplish this, we use the mymodule_preprocess_paragraph__pr_custom
hook and set the array using the #attached
variable. However, when we print the drupalSettings
we are not finding the value passed in. There is no Drupal behavior
used.
How can we pass the value in an array from the mymodule_preprocess_paragraph__pr_custom
into the drupalSettings
variable inside the pr-custom.html.twig
template?
Here is what we tried:
mymodule.module
function mymodule_preprocess_paragraph__pr_custom(&$variables) {
// pass node id.
$node = \Drupal::routeMatch()->getParameter('node');
if($node instanceof \Drupal\node\NodeInterface) {
$variables['elements']['#attached']['drupalSettings']['myArray']['myvar'] = $node->id();
}
}
pr-custom.html.twig
<div>
{{ content.field_text }}
<script>
// this doesn't print myArray and doesn't even have it.
console.log(drupalSettings);
</script>
</div>
hook_page_attachments
. 2) Inline javascript is not recommended, put the javascript in a library, see drupal.stackexchange.com/a/272731/47547hook_page_attachments
did the job.