Attaching libraries

Speaking of using a library, let's see what are some of the more important ways you as a module developer can make use of a library in your code.

The most common way you'll be using libraries is attaching them to your render arrays. Typically, this means that the library is needed for the rendering of that component so that if the said component is missing from the page, the library assets are no longer included.

Here is what a render array would look like with the preceding library we defined attached to it:

    return [      '#theme' => 'some_theme_hook',      '#some_variable' => $some_variable,      '#attached' => [        'library' => [          'my_module/my-library',        ],      ],    ];

The #attached property is important here, and it signifies that we are ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.