function NavigationLinkBlock::build

Builds and returns the renderable array for this block plugin.

If a block should not be rendered because it has no content, then this method must also ensure to return no content: it must then only return an empty array, or an empty array with #cache set (with cacheability metadata indicating the circumstances for it being empty).

Return value

array A renderable array representing the content of the block.

Overrides BlockPluginInterface::build

File

core/modules/navigation/src/Plugin/Block/NavigationLinkBlock.php, line 244

Class

NavigationLinkBlock
Defines a link navigation block.

Namespace

Drupal\navigation\Plugin\Block

Code

public function build() : array {
  $config = $this->configuration;
  $build = [];
  // Ensure that user has access to link before rendering it.
  try {
    $url = Url::fromUri($config['uri']);
    // Internal routes must exist.
    if (!$url->isExternal() && !$url->isRouted()) {
      return $build;
    }
    $access = $url->access(NULL, TRUE);
    if (!$access->isAllowed()) {
      // Cacheable dependency is explicitly added when access is not granted.
      // It is bubbled when the link is rendered.
      $cacheable_metadata = new CacheableMetadata();
      $cacheable_metadata->addCacheableDependency($access);
      $cacheable_metadata->applyTo($build);
      return $build;
    }
  } catch (\InvalidArgumentException) {
    return $build;
  }
  return $build + [
    '#title' => $config['label'],
    '#theme' => 'navigation_menu',
    '#menu_name' => 'link',
    '#items' => [
      [
        'title' => $config['title'],
        'class' => $config['icon_class'],
        'url' => $url,
        'icon' => [
          'icon_id' => $config['icon_class'],
        ],
      ],
    ],
  ];
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.