8.5.x content_translation.module content_translation_page_attachments(&$page)
8.0.x content_translation.module content_translation_page_attachments(&$page)
8.1.x content_translation.module content_translation_page_attachments(&$page)
8.2.x content_translation.module content_translation_page_attachments(&$page)
8.3.x content_translation.module content_translation_page_attachments(&$page)
8.4.x content_translation.module content_translation_page_attachments(&$page)
8.6.x content_translation.module content_translation_page_attachments(&$page)

Implements hook_page_attachments().

File

core/modules/content_translation/content_translation.module, line 560
Allows entities to be translated into different languages.

Code

function content_translation_page_attachments(&$page) {
  $route_match = \Drupal::routeMatch();

  // If the current route has no parameters, return.
  if (!($route = $route_match
    ->getRouteObject()) || !($parameters = $route
    ->getOption('parameters'))) {
    return;
  }

  // Determine if the current route represents an entity.
  foreach ($parameters as $name => $options) {
    if (!isset($options['type']) || strpos($options['type'], 'entity:') !== 0) {
      continue;
    }
    $entity = $route_match
      ->getParameter($name);
    if ($entity instanceof ContentEntityInterface) {

      // Current route represents a content entity. Build hreflang links.
      foreach ($entity
        ->getTranslationLanguages() as $language) {
        $url = $entity
          ->urlInfo()
          ->setOption('language', $language)
          ->setAbsolute()
          ->toString();
        $page['#attached']['html_head_link'][] = array(
          array(
            'rel' => 'alternate',
            'hreflang' => $language
              ->getId(),
            'href' => $url,
          ),
          TRUE,
        );
      }
    }

    // Since entity was found, no need to iterate further.
    return;
  }
}