How to attach a CSS or JS library to a View in Drupal 8
File this one under the 'it's obvious, but only after you've done it' category—I needed to attach a CSS library to a view in Drupal 8 via a custom module so that, wherever the view displayed on the site, the custom CSS file from my module was attached. The process for CSS and JS libraries is pretty much identical, but here's how I added a CSS file as a library, and made sure it was attached to my view:
Add the CSS file as a library
In Drupal 8, drupal_add_css()
, drupal_add_js()
, and drupal_add_library()
were removed (for various reasons), and now, to attach CSS or JS assets to views, nodes, etc., you need to use Drupal's #attached
functionality to 'attach' assets (like CSS and JS) to rendered elements on the page.
In my custom module (custom.module
) or custom theme (custom.theme
), I added the CSS file css/custom_view.css
: