You are here

public function TwigExtension::drupalRegion in Twig Tweak 8

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

Builds the render array of a given region.

Parameters

string $region: The region to build.

string $theme: (Optional) The name of the theme to load the region. If it is not provided then default theme will be used.

Return value

array A render array to display the region content.

File

src/TwigExtension.php, line 110

Class

TwigExtension
Twig extension with some useful functions and filters.

Namespace

Drupal\twig_tweak

Code

public function drupalRegion($region, $theme = NULL) {
  $entity_type_manager = \Drupal::entityTypeManager();
  $blocks = $entity_type_manager
    ->getStorage('block')
    ->loadByProperties([
    'region' => $region,
    'theme' => $theme ?: \Drupal::config('system.theme')
      ->get('default'),
  ]);
  $view_builder = $entity_type_manager
    ->getViewBuilder('block');
  $build = [];
  $cache_metadata = new CacheableMetadata();

  /* @var $blocks \Drupal\block\BlockInterface[] */
  foreach ($blocks as $id => $block) {
    $access = $this
      ->entityAccess($block);
    $cache_metadata = $cache_metadata
      ->merge(CacheableMetadata::createFromObject($access));
    if ($access
      ->isAllowed()) {
      $block_plugin = $block
        ->getPlugin();
      if ($block_plugin instanceof TitleBlockPluginInterface) {
        $request = \Drupal::request();
        if ($route = $request->attributes
          ->get(RouteObjectInterface::ROUTE_OBJECT)) {
          $block_plugin
            ->setTitle(\Drupal::service('title_resolver')
            ->getTitle($request, $route));
        }
      }
      $build[$id] = $view_builder
        ->view($block);
    }
  }
  if ($build) {
    $cache_metadata
      ->applyTo($build);
  }
  return $build;
}