8.5.x theme.api.php hook_page_attachments(array &$attachments)
8.0.x theme.api.php hook_page_attachments(array &$attachments)
8.1.x theme.api.php hook_page_attachments(array &$attachments)
8.2.x theme.api.php hook_page_attachments(array &$attachments)
8.3.x theme.api.php hook_page_attachments(array &$attachments)
8.4.x theme.api.php hook_page_attachments(array &$attachments)
8.6.x theme.api.php hook_page_attachments(array &$attachments)

Add attachments (typically assets) to a page before it is rendered.

Use this hook when you want to conditionally add attachments to a page.

If you want to alter the attachments added by other modules or if your module depends on the elements of other modules, use hook_page_attachments_alter() instead, which runs after this hook.

If you try to add anything but #attached and #cache to the array, an exception is thrown.

Parameters

array &$attachments: An array that you can add attachments to.

See also

hook_page_attachments_alter()

Related topics

1 string reference to 'hook_page_attachments'
PageRenderTest::testHookPageAttachmentsExceptions in core/modules/system/tests/src/Kernel/Common/PageRenderTest.php
Tests hook_page_attachments() exceptions.
9 functions implement hook_page_attachments()

Note: this list is generated by pattern matching, so it may include some functions that are not actually implementations of this hook.

big_pipe_page_attachments in core/modules/big_pipe/big_pipe.module
Implements hook_page_attachments().
book_test_page_attachments in core/modules/book/tests/modules/book_test/book_test.module
Implements hook_page_attachments().
common_test_page_attachments in core/modules/system/tests/modules/common_test/common_test.module
Implements hook_page_attachments().
content_translation_page_attachments in core/modules/content_translation/content_translation.module
Implements hook_page_attachments().
contextual_page_attachments in core/modules/contextual/contextual.module
Implements hook_page_attachments().

... See full list

File

core/lib/Drupal/Core/Render/theme.api.php, line 1017
Hooks and documentation related to the theme and render system.

Code

function hook_page_attachments(array &$attachments) {

  // Unconditionally attach an asset to the page.
  $attachments['#attached']['library'][] = 'core/domready';

  // Conditionally attach an asset to the page.
  if (!\Drupal::currentUser()
    ->hasPermission('may pet kittens')) {
    $attachments['#attached']['library'][] = 'core/jquery';
  }
}

Comments

rho_’s picture

This isn't directly related to this function, but I've found that I've had to do this more than once so thought I would leave a note. There is likely a better way to do this, but I'll often want to check the current path before adding js/css. The path.matcher service helps with this. For example to check for front page:

  if(\Drupal::service('path.matcher')->isFrontPage()) {
    $attachments['#attached']['library'][] = 'mymodule/mylibrary';
  }