0

I need to attach js in all nodes with a specif paragraph bundle. I know how to do this with drupal_add_js, but I prefer don't use it to prevent cache problems.

I am trying with hook preprocess_entity but I don't get it, I don't know how to use the ["#attached"]

function THEME_preprocess_entity(&$variables) { 
  if (isset($variables['paragraphs_item']->bundle) && variables['paragraphs_item']->bundle == "XXXXX") {
   $variables["elements"]["#attached"]['js'][] = array(
                'type' => 'file',
                'data' => 'myfile.js',
              );
      }
    }

What am I doing wrong?

1
  • 1
    I don't know how to use the ["#attached"] did you refer to the Drupal 7 documentation on this?
    – Kevin
    Commented Dec 18, 2018 at 16:07

2 Answers 2

0

Try this code for attaching

$variables['#attached']['js'][] = 'myfile.js';

Or

$variables['#attached']['library'][] = 'myfile.js';
1
  • Thanks to answer me, but don't works
    – SilviaGDLR
    Commented Dec 19, 2018 at 6:23
0

Finally I got, I have to add ['content'] before ['#attached']

function THEME_preprocess_entity(&$variables) { 
  if (isset($variables['paragraphs_item']->bundle) && variables['paragraphs_item']->bundle == "XXXXX") {
    $variables["content"]["#attached"]['js'][] = array(
       'type' => 'file',
       'data' => 'myFile.js',
    );
  }
 }

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.