function hook_page_attachments

Same name in other branches
  1. 8.9.x core/lib/Drupal/Core/Render/theme.api.php \hook_page_attachments()
  2. 10 core/lib/Drupal/Core/Render/theme.api.php \hook_page_attachments()
  3. 11.x core/lib/Drupal/Core/Render/theme.api.php \hook_page_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. This hook can only be implemented by modules.

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.
12 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 1048

Code

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

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.