0

I am new to Drupal, but I am very familiar with WordPress.

In WordPress, I am able to hook into the head of a document with wp_head to add things like page specific meta tags.

When using a custom theme based on Stable, how would you add page specific things in the <head> of a document in Drupal 8?

Note: I am wondering how this would be done without a custom module.

1 Answer 1

1

You can attach the tag to the page's render array via hook_page_attachments_alter().

An example from the related change record:

function MYTHEME_page_attachments_alter(array &$page) {
    $viewport = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
            'name' => 'viewport',
            'content' => 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
        ),
    );
    $page['#attached']['html_head'][] = [$viewport, 'viewport'];
}
2
  • Nice. Where would I be able to find all of the # keys available to me? I viewed the contents of $page and it looks like I have one key #attached with library, html_head_link, html_head as sub keys. Are there others that I could add? Jul 3, 2017 at 13:10
  • 1
    Anywhere, really - the # properties are arbitrary, they describe meta info about the render array and can be literally any valid string that starts with a #. The method that renders whatever element type the property is on decides what to do with it. It's better to approach it as "what do I need to do?" rather than "what are all the things I could do?", as it's basically infinite by nature
    – Clive
    Jul 3, 2017 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.