模块中 Drupal 7 的 "drupal_add_html_head" 对应的 Drupal 8 是什么?

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

我正在为 Drupal 8 创建一些自定义模块。它们包括一些 header 修改以更好地集成 Facebook。这是它在 Drupal 7 中的样子(七):

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

但是这个 drupal_add_html_head 函数在 Drupal 8 中早就消失了。我完全不知道从哪里开始攻击它。也许是 "Headerbag"?有一个Headerbag::add。也许它在模块的 return 变量中,可能在此处的某处添加另一个元素:

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

也许HtmlResponseAttachmentsProcessor::setHeaders? HeaderBag::set? Session::setRequestHeader? PoStreamWriter::setHeader? PoMetadataInterface::setHeader?

不幸的是,我几乎找不到关于如何使用它们的示例。我相信这里的每个人都熟悉这样的烦恼,即在以前的版本中 有效 的代码在新代码中变成 "doesn't work with no solution"。

您可以使用 your_module_page_attachments 挂钩。例如,如果您想调整 og:image 标签,您可以执行以下操作:

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'];
}

挂钩信息:https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook_page_attachments/8.2.x

首选的替代方法是在构建数组中使用 #attached 属性。

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

这是详细说明此内容的更改记录:https://www.drupal.org/node/2160069