/Drupal 8

function hook_page_attachments

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

Define functions that alter the behavior of Drupal core.


core/lib/Drupal/Core/Render/theme.api.php, line 1015
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';

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.