You are here

public function TwigExtension::drupalBlock in Twig Tweak 8

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

Builds the render array for the provided block.

Parameters

mixed $id: The ID of the block to render.

bool $check_access: (Optional) Indicates that access check is required.

Return value

null|array A render array for the block or NULL if the block does not exist.

File

src/TwigExtension.php, line 82

Class

TwigExtension
Twig extension with some useful functions and filters.

Namespace

Drupal\twig_tweak

Code

public function drupalBlock($id, $check_access = TRUE) {
  $entity_type_manager = \Drupal::entityTypeManager();
  $block = $entity_type_manager
    ->getStorage('block')
    ->load($id);
  if ($block) {
    $access = $check_access ? $this
      ->entityAccess($block) : AccessResult::allowed();
    if ($access
      ->isAllowed()) {
      $build = $entity_type_manager
        ->getViewBuilder('block')
        ->view($block);
      CacheableMetadata::createFromRenderArray($build)
        ->merge(CacheableMetadata::createFromObject($block))
        ->merge(CacheableMetadata::createFromObject($access))
        ->applyTo($build);
      return $build;
    }
  }
}