function LanguageBlock::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/ language/ src/ Plugin/ Block/ LanguageBlock.php, line 88
Class
- LanguageBlock
- Provides a 'Language switcher' block.
Namespace
Drupal\language\Plugin\BlockCode
public function build() {
$build = [];
$type = $this->getDerivativeId();
$route_match = \Drupal::routeMatch();
// If there is no route match, for example when creating blocks on 404 pages
// for logged-in users with big_pipe enabled using the front page instead.
if ($this->pathMatcher
->isFrontPage() || !$route_match->getRouteObject()) {
// We are skipping the route match on both 404 and front page.
// Example: If on front page, there is no route match like when creating
// blocks on 404 pages for logged-in users with big_pipe enabled, use the
// front page.
$url = Url::fromRoute('<front>');
}
else {
$url = Url::fromRouteMatch($route_match);
}
$links = $this->languageManager
->getLanguageSwitchLinks($type, $url);
// In any render cache items wrapping this block, account for variations
// by user access to each switcher link, the current path and query
// arguments, and language negotiation.
$cache_metadata = BubbleableMetadata::createFromRenderArray($build)->addCacheContexts([
'url.path',
'url.query_args',
'url.site',
'languages:' . $type,
]);
if (isset($links->links)) {
$build = [
'#theme' => 'links__language_block',
'#links' => $links->links,
'#attributes' => [
'class' => [
"language-switcher-{$links->method_id}",
],
],
'#set_active_class' => TRUE,
];
foreach ($links->links as $link) {
if ($link['url'] instanceof Url) {
$cache_metadata->addCacheableDependency($link['url']->access(NULL, TRUE));
}
}
}
$cache_metadata->applyTo($build);
return $build;
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.