Skip to content

Instantly share code, notes, and snippets.

@steffenr
Created August 12, 2016 11:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save steffenr/a66d4d67af70bd866c5af1b459a46cb9 to your computer and use it in GitHub Desktop.
Save steffenr/a66d4d67af70bd866c5af1b459a46cb9 to your computer and use it in GitHub Desktop.
Attach a CSS or JS library to a View in Drupal 8
custom_view:
css:
component:
css/custom_view.css: {}
<?php
/**
* Implements hook_views_pre_render().
*/
function custom_views_pre_render(ViewExecutable $view) {
if (isset($view) && ($view->storage->id() == 'my_view')) {
$view->element['#attached']['library'][] = 'custom/custom_view';
}
}
@gwagroves
Copy link

$view->id() returns the view id, without having to access the content storage.

@domaalex
Copy link

domaalex commented Oct 24, 2017

this works for me

function MODULENAME_views_pre_render(\Drupal\views\ViewExecutable $view) {
}

@hplord12
Copy link

hplord12 commented Mar 6, 2018

you can check this module "https://www.drupal.org/project/views_attach_library" to attach CSS or JS library to a View in Drupal 8

@com2
Copy link

com2 commented May 11, 2018

I understand that custom_view is the library name as defined in mymodule.libraries.yml. But where is custom defined in view->element['#attached']['library'][] = 'custom/custom_view'; ? Is that hardcoded? I had the impression it had to be the module name.

@BryanGullan
Copy link

@com2 the first part of the library ("custom", here) is the name of the module or theme which provides the library. So for the example above, it should be mymodule/custom_view

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment