Skip to main content

Drupal 9 - Assign a block to a region in theme template file

Drupal 8 & Drupal 9 uses object oriented hierarchy to assign a block to a region in a theme template file. When you need to assign a block to a region, Drupal 7 used to have a function called block_get_blocks_by_region(), starting Drupal 8 there was no specific function that can do this. Drupal 9 follows the same Object oriented hierarchy model to do the same however, there is slight change in the code due to the deprecated classes & functions. Follow the code below to understand how to assign a block to a region in your theme template file.

You can create a custom module or you can define this code in a theme preprocessor function to achieve this.

Drupal 7:

Use the block_get_blocks_by_region() function.

 

 

Drupal 8:

 

 

function your_custom_module_get_blocks_by_region($region) {

  $blocks = \Drupal::entityTypeManager()

    ->getStorage('block')->loadByProperties([

      'theme' => \Drupal::theme()->getActiveTheme()->getName(),

      'region' => $region,

    ]);

  uasort($blocks, 'Drupal\block\Entity\Block::sort');

  $build = [];

  foreach ($blocks as $key => $block) {

    if ($block->access('view')) {

      $build[$key] = entity_view($block, 'block');

    }

  }

   return $build;

}

 

 

 

 

}

 

Drupal 9:

 

function your_custom_module_get_blocks_by_region($region) {

  $blocks = \Drupal::entityTypeManager()

    ->getStorage('block')->loadByProperties([

      'theme' => \Drupal::theme()->getActiveTheme()->getName(),

      'region' => $region,

    ]);

  uasort($blocks, 'Drupal\block\Entity\Block::sort');

  $build = [];

  foreach ($blocks as $key => $block) {

    if ($block->access('view')) {

      $build[$key] = entity_view($block, 'block');

// in Drupal 9 first create a block view builder then assign to region variable.

 $block_view = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);

              $build[$key] = $block_view;

   }

  }

   return $build;

}