You are here

public function NodeViewController::view in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/node/src/Controller/NodeViewController.php \Drupal\node\Controller\NodeViewController::view()
  2. 10 core/modules/node/src/Controller/NodeViewController.php \Drupal\node\Controller\NodeViewController::view()

Provides a page to render a single entity.

Parameters

\Drupal\Core\Entity\EntityInterface $_entity: The Entity to be rendered. Note this variable is named $_entity rather than $entity to prevent collisions with other named placeholders in the route.

string $view_mode: (optional) The view mode that should be used to display the entity. Defaults to 'full'.

Return value

array A render array as expected by \Drupal\Core\Render\RendererInterface::render().

Overrides EntityViewController::view

File

core/modules/node/src/Controller/NodeViewController.php, line 70

Class

NodeViewController
Defines a controller to render a single node.

Namespace

Drupal\node\Controller

Code

public function view(EntityInterface $node, $view_mode = 'full', $langcode = NULL) {
  $build = parent::view($node, $view_mode, $langcode);
  foreach ($node
    ->uriRelationships() as $rel) {
    $url = $node
      ->toUrl($rel)
      ->setAbsolute(TRUE);

    // Add link relationships if the user is authenticated or if the anonymous
    // user has access. Access checking must be done for anonymous users to
    // avoid traffic to inaccessible pages from web crawlers. For
    // authenticated users, showing the links in HTML head does not impact
    // user experience or security, since the routes are access checked when
    // visited and only visible via view source. This prevents doing
    // potentially expensive and hard to cache access checks on every request.
    // This means that the page will vary by user.permissions. We also rely on
    // the access checking fallback to ensure the correct cacheability
    // metadata if we have to check access.
    if ($this->currentUser
      ->isAuthenticated() || $url
      ->access($this->currentUser)) {

      // Set the node path as the canonical URL to prevent duplicate content.
      $build['#attached']['html_head_link'][] = [
        [
          'rel' => $rel,
          'href' => $url
            ->toString(),
        ],
        TRUE,
      ];
    }
    if ($rel == 'canonical') {

      // Set the non-aliased canonical path as a default shortlink.
      $build['#attached']['html_head_link'][] = [
        [
          'rel' => 'shortlink',
          'href' => $url
            ->setOption('alias', TRUE)
            ->toString(),
        ],
        TRUE,
      ];
    }
  }

  // Since this generates absolute URLs, it can only be cached "per site".
  $build['#cache']['contexts'][] = 'url.site';

  // Given this varies by $this->currentUser->isAuthenticated(), add a cache
  // context based on the anonymous role.
  $build['#cache']['contexts'][] = 'user.roles:anonymous';
  return $build;
}