hook_page_attachments() not called from mytheme.theme file 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 &amp;$attachments) {
  $attachments ['#attached']['library'][] = 'mytheme/general-js';
}
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(&amp;$page) {
  $page['#attached']['library'][] = 'mytheme/general-js';
}


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

function mytheme_preprocess_page(&amp;$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.