Add a custom library via preprocess

Where I work, we build all of our sites using the Paragraphs module. It lets us be flexible in our designs and is easy for clients to create robust pages. Normally, each layout will have its own library with the related CSS & JS. That is usually included in the paragraph template, something like this:

{{ attach_library('theme/image_gallery') }}

<section class="image-gallery">
 // ...
</section>

That works for most cases, but sometimes you have a slightly more complicated example. What if you have a component that is a slider, but the number of slides is variable? You don't want to load the extra JS if there is only one image, since it won't be a slider. You could write some conditionals in twig, but I prefer a nice clean approach in a preprocess function.

function theme_preprocess_paragraph(&$variables) {
  $paragraph = $variables['paragraph'];
  $image_count = 0;

  // Check bundle for image field.
  if ($paragraph->hasField('field_images')) {
    // Get number of images from field.
    $image_count = $paragraph->field_images->count();
  }

  // If there is more than one image layout is a slider.
  if ($image_count > 1) {
    $variables['#attached']['library'][] = 'theme/slider';
  }
}
Posted March 23rd, 2020
Tested againstDrupal 8.8.4