4

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.

MotoRidingMelon
  • 2,347
  • 2
  • 21
  • 28

2 Answers2

3

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

Frank Drebin
  • 1,063
  • 6
  • 11
  • Is there additional work in the routing.yml to trigger the call to your_module_page_attachments? – MotoRidingMelon Apr 28 '16 at 13:02
  • No, you create a "your_module.module" file, where "your_module" is of course the name of your module. In that file you declare the function from above, again replace "your_module" with your module name. Then just clear the cache and it should work. – Frank Drebin Apr 28 '16 at 20:30
1

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

pianomansam
  • 111
  • 3
  • 1
    THanks. Does it say something about Drupal that I get an answer 5 years later, after the site in question has been migrated to version 9? :( Honestly, I can't remember if I got it working, and I can only suspect FB has gotten ever more closed in their approach to integrating external content. – MotoRidingMelon Apr 05 '21 at 23:53
  • There is dedicated site for Drupal answers : https://drupal.stackexchange.com – salah-1 Apr 08 '21 at 11:25