Drupal 8: How to get all blocks in a region to use the same template

2.3k views Asked by At

So what I am trying to do, is to get all the blocks in footer region to use the same template, say, block--footer-block.html.twig.

What I tried is to use hook_theme_suggestions_HOOK_alter() to check where the blocks are located and add the region name to the template suggestions.

/**
* Implements hook_theme_suggestions_HOOK_alter().
* */
function mytheme_theme_suggestions_block_alter(array &$suggestions, array 
$variables {
    $block = Block::load($variables['elements']);
    $region = $block->getRegion();
    $suggestions[] = 'block . '__' . $region . '__block';
}

Currently the $block->getRegion(); breaks my site - no idea why. It doesn't even give any errors, the site is just blank.

Is this even a good way of doing this?

2

There are 2 answers

0
stacey.mosier On

This was answered here: https://drupal.stackexchange.com/questions/192616/how-to-make-a-theme-hook-suggestion-for-blocks-according-to-region

function mytheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  $block = Block::load($variables['elements']['#id']);
  $region = $block->getRegion();
  $suggestions[] = 'block__'.$region.'__block'; 
}
0
eliosh On

You can also use this snippet, in your hook_theme_suggestions_HOOK_alter:

if (isset($variables['elements']['#configuration']['region'])) {
    $region = $variables['elements']['#configuration']['region'];
    $suggestions[] = 'block__' . $region;
    if (isset($variables['elements']['#configuration']['provider'])) {
      $provider = $variables['elements']['#configuration']['provider'];
      $suggestions[] = 'block__' . $region . '__' . $provider;
    }
  }

Reference