2

I wanted to add a library to a specific paragraph bundle. I know I can do {{ attach_library('my_theme/my-library-name') }} using twig, but that means I have to create a file for each bundle. The goal is to be able to use just the my_theme.theme file to add the library.

Question

How to add library to Paragraph bundle using hook_preprocess_theme?

Here is what we tried, but it didn't work even after cache clear.

function mytheme_preprocess_paragraphs(&$variables) {
  $elements = $variables['elements'];
  $paragraph = $elements['#paragraph'];
  if(isset($paragraph) {
    $paragraph_bundle = $paragraph->getParagraphType()->id();
    switch($paragraph_bundle) {
      case 'my_bundle':
        $variables['elements']['#attached']['library'][] = 'my_theme/my-library-name';
        break;
    }
  }
}

1 Answer 1

7

You need to set $variables['#attached']['library'] instead of $variables['elements']['#attached']['library'].

The code shown in the question becomes the following one.

function mytheme_preprocess_paragraphs(&$variables) {
  $elements = $variables['elements'];
  $paragraph = $elements['#paragraph'];

  if (isset($paragraph)) {
    $paragraph_bundle = $paragraph->getParagraphType()->id();
    switch($paragraph_bundle) {
      case 'my_bundle':
        $variables['#attached']['library'][] = 'my_theme/my-library-name';
        break;
    }
  }
}
1
  • 2
    Yes, in a preprocess hook the top level is the only supported place to add attachments, because deeper levels of $variables are already preprocessed by core or might by contrib/custom code.
    – 4uk4
    Commented Dec 16, 2019 at 23:12

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.