Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Drupal 8 equivalent of Drupal 7's "drupal_add_html_head" within a module?

I'm creating some custom modules for Drupal 8. They include some header modification for better Facebook integration. Here is what it looked like in Drupal 7 (SEVEN):

    $element1 = array
        (
        '#tag' => 'meta',
        '#attributes' => array
            ( 
            'property' => 'og:title',
            'content' => " Profile: " . $record->NameFirst . " " . $record->NameLast,
            ),
        );
    drupal_add_html_head($element1, 'og_title');

But this drupal_add_html_head function is long long gone in Drupal 8. And I'm quite lost as to where to START attacking this. Maybe it's "Headerbag"? There's a Headerbag::add. Maybe it's in the module's return variable, possibly adding another element somewhere here:

return array(
  '#markup' => t($pageContent),
);

Maybe HtmlResponseAttachmentsProcessor::setHeaders? HeaderBag::set? Session::setRequestHeader? PoStreamWriter::setHeader? PoMetadataInterface::setHeader?

Unfortunately, I can find pretty much no examples of how these are used. And I'm sure everyone here is familiar with the annoyance of having code that does work in previous versions that morphs into "doesn't work with no solution" in new code.

like image 501
Anders8 Avatar asked Oct 23 '25 16:10

Anders8


2 Answers

You can use the your_module_page_attachments hook. For example if you want to adjust the og:image tag you could do the following:

function your_module_page_attachments(array &$page) {
    $ogImage = array(
        '#tag' => 'meta',
        '#attributes' => array(
            'property' => 'og:image',
            'content' => url to your image,
        ),
    );

    $page['#attached']['html_head'][] = [$ogImage, 'ogImage'];
}

Hook information: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook_page_attachments/8.2.x

like image 108
Frank Drebin Avatar answered Oct 27 '25 03:10

Frank Drebin


The preferred replacement is to use the #attached property in the build array.

$build['#attached']['html_head'][] = array(
...
);

Here is the change record detailing this: https://www.drupal.org/node/2160069

like image 42
pianomansam Avatar answered Oct 27 '25 03:10

pianomansam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!