W3cubDocs

/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.

Parameters

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

See also

hook_page_attachments_alter()

Related topics

Hooks
Define functions that alter the behavior of Drupal core.

File

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

© 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.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook_page_attachments/8.1.x