Drupal8 attaching libraries to specific pages

Submitted by AppCreator on Sat, 11/07/2015 - 15:56

Drupal 8 is just days away from stable release and I have finally had a chance to play.
It's a full rewrite so lots of changes, the admin interface seems much cleaner.
This is a short note on attaching libraries in a custom theme.
JavaScript and Stylesheets get attached via libraries which are defined in the {theme-name}.libraries.yml file.
which could look something like:

global-styling:
version: VERSION
css:
base:
css/theme/blocks.css: {}
code-highlight:
version: 1.x
css:
theme:
css/code_highlight.css: {}
js:
js/code_highlight.js: {}
prettyprint:
remote: //cdn.rawgit.com/google/code-prettify
license:
name: Apache 2
gpl-compatible: true
js:
//cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?skin=sunburst: { type: external}
domcheck:
js:
js/domcheck.js: {}

Once defined you can attach to all pages via the {theme-name}.info.yml file.

libraries:
- theme-name/global-styling

Or to specific pages through preprocess hooks in the {theme-name}.theme file, the Drupal 8 replacement for template.php.


function appcreator_preprocess_node(&$variables) {
// get a hold of the node object
$node = \Drupal::routeMatch()->getParameter('node');
if ($node) { // check we have a node object.
if ($node->id() == 90) { // look for a specific node id.
//attach the library.
$variables['#attached']['library'][] = 'them-name/domcheck';
}
//load a library if a term exists.
$terms = $node->taxonomy_vocabulary_1;
if (is_object($terms)) { if we have terms.
foreach( $terms as $delta => $term) {
if ($term->target_id == 31) { //See if we have a specific term id.
$variables['#attached']['library'][] = 'theme-name/code-highlight';
$variables['#attached']['library'][] = 'theme-name/prettyprint';
}
}
}
}
}

Attaching a library will automatically attach both the JavaScript and Stylesheets defined in the library. If your JavaScript files require jQuery or have any other dependency you need to define them in the library.

dependencies:
- core/jquery
As by default no JavaScript libraries are attached for anonymous visitors.