I am trying to load a custom css and js on my content type's view mode. Can this be achieved in drupal 8?
1 Answer
Yes. You can create a new library as follows:
[THEME].libraries.yml
mycontenttype:
css:
theme:
path/to/my.file.css: {}
js:
path/to/my.file.js: {}
Next, you attach that library to the node in hook_node_view_alter():
function THEME_node_view_alter(array &$build, Drupal\node\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
// Check the content type (bundle) and view mode:
if ($entity->bundle() == 'mycontenttype' && $build['#view_mode'] == 'myviewmode') {
// Attach your library in the form of MODULEKEY/LIBRARYKEY
$build['#attached']['library'][] = 'mymodule/mycontenttype';
}
}
Now your CSS and JS will be rendered on the page if/when a node of the given content type is rendered on the page with the given view mode.