0

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>
  • 1
    1) In this hook you can only add the node id of the parent entity to drupalSettings, not a route parameter. For this use a more global hook like hook_page_attachments. 2) Inline javascript is not recommended, put the javascript in a library, see drupal.stackexchange.com/a/272731/47547 – 4k4 Feb 20 at 7:22
  • @4k4 moving it to the hook_page_attachments did the job. – usernameabc Mar 7 at 23:15
0

Wish I could comment...

Are you sure your hook is running? the instanceof operator is not implemented correctly so you should be seeing an error when the hook tries to run.

Also, you may not need to add 'drupalSettings' to the 'elements' key. You should be able to put it on the top level of $variables.

  • the instance of was a typo and has been corrected on the question. Putting it in the top level or parent entity as mentioned by @4k4 did the job. – usernameabc Mar 4 at 18:39
  • $variables['#attached']['drupalSettings']['blah']... works. – simesy May 20 at 5:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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