You are here

function metatag_page_attachments in Metatag 8

Implements hook_page_attachments().

Load all meta tags for this page.

File

./metatag.module, line 117
Contains metatag.module.

Code

function metatag_page_attachments(array &$attachments) {
  if (!metatag_is_current_route_supported()) {
    return NULL;
  }
  $metatag_attachments =& drupal_static('metatag_attachments');
  if (is_null($metatag_attachments)) {

    // Load the meta tags from the route.
    $metatag_attachments = metatag_get_tags_from_route();
  }
  if (!$metatag_attachments) {
    return NULL;
  }

  // Trigger hook_metatags_attachments_alter().
  // Allow modules to rendered metatags prior to attaching.
  \Drupal::service('module_handler')
    ->alter('metatags_attachments', $metatag_attachments);

  // If any Metatag items were found, append them.
  if (!empty($metatag_attachments['#attached']['html_head'])) {
    if (empty($attachments['#attached'])) {
      $attachments['#attached'] = [];
    }
    if (empty($attachments['#attached']['html_head'])) {
      $attachments['#attached']['html_head'] = [];
    }
    $head_links = [];
    foreach ($metatag_attachments['#attached']['html_head'] as $item) {

      // Do not attach a title meta tag as this unnecessarily duplicates the
      // title tag.
      // @see metatag_preprocess_html()
      if ($item[1] == 'title') {
        continue;
      }
      $attachments['#attached']['html_head'][] = $item;

      // Also add a HTTP header "Link:" for canonical URLs and shortlinks.
      // See HtmlResponseAttachmentsProcessor::processHtmlHeadLink() for the
      // implementation of the functionality in core.
      if (isset($item[0]['#attributes']['href'])) {
        if (in_array($item[1], [
          'canonical_url',
          'shortlink',
        ])) {
          $attributes = $item[0]['#attributes'];
          $href = '<' . Html::escape($attributes['href']) . '>';
          unset($attributes['href']);
          $param = HtmlResponseAttachmentsProcessor::formatHttpHeaderAttributes($attributes);
          if (!empty($param)) {
            $href .= ';' . $param;
          }
          $head_links[] = $href;
        }
      }
    }

    // If any HTTP Header items were found, add them too.
    if (!empty($head_links)) {
      $attachments['#attached']['http_header'][] = [
        'Link',
        implode(', ', $head_links),
        FALSE,
      ];
    }
  }
}