Drupal - Add CSS/JS to particular view?

but what does $variables contain?

A couple of render arrays and some values that be used by twig template. Your best option is check de documentation for each preprocess function to see what are included in $variables. Docs link template_preprocess(&$var) better explanation about preprocess functions and default list of template preprocess functions

but how do I apply this to views or content types?

For me the best option is your twig template file by including this line.

{{ attach_library('my_theme/my-library') }}

No matter how many times this will be 'attached' only one will be downloaded (or aggregate). And only will added if this particular template will be rendered.

More info about Twig debug is here


One way to do it via your theme:

Set up your js as a library in your mytheme.libraries.yml file:

library-name:
  js:
    js-file-location/js-file-name.js: {}

Call your library in a preprocess hook in your mytheme.theme file:

/**
 * Implements hook_preprocess_views_view().
 */
function mytheme_preprocess_views_view(&$vars) {
  $vars['#cache']['contexts'][] = 'route';
  if ($vars['view_array']['#name'] == 'view_name') {
    $vars['#attached']['library'][] = 'mytheme/library-name';
  }
}

You'll need to replace these parts with your own actual code:

  • js-file-location - is it in a folder?
  • js-file-name - include the extension, I've used .js in this example
  • library-name - call it whatever you like
  • mytheme - the machine name of your theme

Note the cache context in this example is set to cache per route. It's important to know about it but outside the scope of this question.

Source: Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme

Tags:

Theming

8