Views Attach Library module: Drupal 8
The drupal_add_css(), drupal_add_js(), and drupal_add_library() were removed from Drupal 8 for various reasons. Thus to attach CSS or JS assets to views, nodes, etc., Drupal's #attached functionality had to be applied to 'attach' assets (like CSS and JS) to rendered elements on the page. Previously we used the hook_views_pre_render() hook method to attach a library in the view. Let's explore this recently contributed module by QED42, the 'Views Attach Library'.
Views Attach Library module is designed to attach JS and CSS library in views, by merely mentioning the library name. It provides a simple UI option in the views where a user has to simply mention the libraries name.
| Benefits of Views Attach Library module
- Easily attach libraries to any view’s page or block.
- Add single as well as multiple libraries in views.
- Easy to configure.
- Instead of writing custom coding to attach library in views, this module provides you simple configuration UI in views UI.
| Implementing the Views Attach Library
To implement this, I attached a CSS or JS library to a view in Drupal 8 via a custom module such that, wherever the view is displayed on a site, the custom CSS and JS file from my module were attached automatically.
The module provides a simple UI option in all view pages and blocks. We can upload single as well as multiple libraries just by declaring the libraries name in the UI textfield.
| How does it work?
Installation is as simple as copying the module into your 'modules' contrib directory and then enabling the module.
To add the library in view follow the below steps:
- Create or edit view
- Find Attach Library section
- Click on Add Library or Edit Library
- Add or edit library name in textfield.
| Using views_attach_library module
Let’s understand the application of this module via an example.
Consider a custom module called ‘abc’ and this module has a library called ‘abc-js’ and this library has one CSS(abc.css) and two JS(abc1.js, abc2.js) files.
Now add ‘portal_abc/abc-js’ in the textfield which is nothing but a library name, where ‘abc’ is the module or theme name and ‘abc-js’ is the library name.
In this way, the view will now include one CSS(abc.css) and two JS(abc1.js, abc2.js) file.
Check out this video for a step-by-step implementation of the Views Attach Library module.
| Developer support
Hardik Patel - https://www.drupal.org/user/3316709/
Yogesh Chougule - https://www.drupal.org/user/724666/
Rahul Lamkhade - https://www.drupal.org/user/2718915/
| Module download link
Check out the Views Attach Library module here - https://www.drupal.org/project/views_attach_library