You are here

public function TwigExtension::drupalBlock in Twig Tweak 8.2

Same name and namespace in other branches
  1. 8 src/TwigExtension.php \Drupal\twig_tweak\TwigExtension::drupalBlock()

Builds the render array for a block.

Parameters

mixed $id: The string of block plugin to render.

array $configuration: (optional) Pass on any configuration to the plugin block.

bool $wrapper: (optional) Whether or not use block template for rendering.

Return value

null|array A render array for the block or NULL if the block cannot be rendered.

File

src/TwigExtension.php, line 456

Class

TwigExtension
Twig extension with some useful functions and filters.

Namespace

Drupal\twig_tweak

Code

public function drupalBlock($id, array $configuration = [], $wrapper = TRUE) {
  $configuration += [
    'label_display' => BlockPluginInterface::BLOCK_LABEL_VISIBLE,
  ];

  /** @var \Drupal\Core\Block\BlockPluginInterface $block_plugin */
  $block_plugin = \Drupal::service('plugin.manager.block')
    ->createInstance($id, $configuration);

  // Inject runtime contexts.
  if ($block_plugin instanceof ContextAwarePluginInterface) {
    $contexts = \Drupal::service('context.repository')
      ->getRuntimeContexts($block_plugin
      ->getContextMapping());
    \Drupal::service('context.handler')
      ->applyContextMapping($block_plugin, $contexts);
  }
  $access = $block_plugin
    ->access(\Drupal::currentUser(), TRUE);
  if (!$access
    ->isAllowed()) {
    return;
  }

  // Title block needs special treatment.
  if ($block_plugin instanceof TitleBlockPluginInterface) {
    $request = \Drupal::request();
    $route_match = \Drupal::routeMatch();
    $title = \Drupal::service('title_resolver')
      ->getTitle($request, $route_match
      ->getRouteObject());
    $block_plugin
      ->setTitle($title);
  }
  $build['content'] = $block_plugin
    ->build();
  if ($block_plugin instanceof TitleBlockPluginInterface) {
    $build['content']['#cache']['contexts'][] = 'url';
  }
  if ($wrapper && !Element::isEmpty($build['content'])) {
    $build += [
      '#theme' => 'block',
      '#id' => $configuration['id'] ?? NULL,
      '#attributes' => [],
      '#contextual_links' => [],
      '#configuration' => $block_plugin
        ->getConfiguration(),
      '#plugin_id' => $block_plugin
        ->getPluginId(),
      '#base_plugin_id' => $block_plugin
        ->getBaseId(),
      '#derivative_plugin_id' => $block_plugin
        ->getDerivativeId(),
    ];
  }
  CacheableMetadata::createFromRenderArray($build)
    ->merge(CacheableMetadata::createFromObject($access))
    ->merge(CacheableMetadata::createFromObject($block_plugin))
    ->applyTo($build);
  return $build;
}