Attach a Library for Drupal 8, Drupal 9

Last updated July 12, 2019

Libraries can be attached to all pages, a subset of pages, or to elements in a render array. This allows you to have some assets that are global, and others that are only loaded on an as-needed basis.

In this tutorial, we'll look at attaching asset libraries:

  • Globally, via your file
  • Conditionally, via a preprocess function using the #attached render array property
  • Inside of a Twig template file

By the end of this tutorial you should be able to attach asset libraries in various different ways depending on your use case.