5

I am trying to load an asset library in my Drupal 8 custom theme. I have created the library and can load it via mytheme.info.yml file. However, if I try the load it using hook_page_attachments() in the mytheme.theme file, then the function is not called.

I did a search for this function in the Drupal 8 standard installation and it only ever seems to be called from modules. Can hook_page_attachments only be called from modules? Any suggestions on why this is not working.

mytheme.theme file content:

function mytheme_page_attachments(array &$attachments) {
  $attachments ['#attached']['library'][] = 'mytheme/general-js';
}

1 Answer 1

11

It appears that this function is only callable from a module, as it is listed in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module but not listed as a valid method in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.

It should be noted that the related function hook_page_attachments_alter() can be called from the theme layer (i.e. can be called from mytheme.theme file).

function mytheme_page_attachments_alter(&$page) {
  $page['#attached']['library'][] = 'mytheme/general-js';
}

Alternatively one can attach libraries to a page from within hook_preprocess_page()

function mytheme_preprocess_page(&$variables) {
  $variables['#attached']['library'][] = 'mytheme/cuddly-slider';
}

The advantage of these two methods is that it enables one to utilize logic/code to determine whether or not to attach a library to a page.

2
  • Another bennefit of using these methods is attaching inline scripts to the head of a page. For example, the "advanced" typekit script, or a google analytics script you want to manually code in. Good instructions on how to here: drupal.org/node/2642476#comment-11838322 May 17, 2017 at 14:01
  • A bit misleading, that hook_page_attachments is placed in theme.api.php: api.drupal.org/api/drupal/…
    – NicklasF
    Feb 17, 2023 at 21:23

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.