3

I've been trying to add css to a content type for a while, but I can't seem to find any help on this for drupal 8.

How do you add a library to only the nodes of a content type?

Thanks in advance!

1 Answer 1

7

The generic answer:

if (some condition) {
  $something['#attached']['library'][] = 'yourmodule/yourlibrary';
}

If you're in a module, do it in hook_node_view() and add it to $build. If you're in a theme, do it in hook_preprocess_node() and add it to $variables.

some_condition for your case would be $node->getType() == 'your_type', in case of preprocess, the node object is in $variables['node']

You can even do it directly within a template with attach_library(), see https://www.drupal.org/node/2456753.

7
  • Thanks @Berdir. I sorry I didn't mention it earlier, but I am doing this for theme and preprocess_page(&$variables). However, I still can't get it to work. I ended up with something like this: function THEME_preprocess_page(&$variables) { $node == $variables['node']; if ($node->getType() == 'CONTENT-TYPE') { $variables['#attached']['library'][] = 'THEME/LIBRARY'; } } This results in "Fatal error: Call to a member function getType() on a non-object" Commented Sep 4, 2016 at 21:38
  • You're doing it in preprocess_page(). As I said, you should do it in preprocess_node(). You have a fatal because not all pages have a node. But preprocess_node() is only called if you actually have a node. So either check that you have a node object or move it to the correct preprocess. Note that you might want to check the view mode as well, depending on whether it should only be added to full, teaser or whatever...
    – Berdir
    Commented Sep 4, 2016 at 21:42
  • I'm sure I'm missing someting, but function THEME_preprocess_node(&$variables) { if ($node->getType() == 'CONTENT_TYPE') { $variables['#attached']['library'][] = 'THEME/LIBRARY'; } } still returns the same fatal error. Commented Sep 4, 2016 at 21:48
  • You are missing something yes, you're not defining $node anymore.
    – Berdir
    Commented Sep 4, 2016 at 21:59
  • With or without it, it doesn't work. Rephrased: function crimesto_preprocess_node(&$variables) { $node == $variables['node']; if ($node->getType() == 'wanted') { $variables['#attached']['library'][] = 'crimesto/wanted_print'; } } doesn't work... Commented Sep 4, 2016 at 22:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.