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';
  }
}
doc_Drupal
2016-10-29 09:18:25
Comments
Leave a Comment

Please login to continue.