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.


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

See also


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


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


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';