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!
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.
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
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
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