To preprocess all blocks in theme named Scriptun we will use function scriptun_theme_suggestions_block_alter in scriptun.theme file.
Problem is that there is no region id inside variables array (let me know if you can find it, I couldn't). So we need to load it:
// /themes/scriptun/scriptun.theme
function scriptun_theme_suggestions_block_alter(array &$suggestions, array $variables){
if (!empty($variables['elements']['#id'])) {
$block = \Drupal\block\Entity\Block::load($variables['elements']['#id']);
$region = $block->getRegion();
// adds suggestion with region and block id
$suggestions[] = 'block__' . $region . '__' . $variables['elements']['#id'];
// adds suggestion with region id
$suggestions[] = 'block__' . $region;
}
}
Under elements->#id key we have block id so we can load it and get region. After this, you will have additional suggestions for any block.
More extended suggestions
If you use regions with number suffix like footer_1, footer_2 you can add additional suggestion without numbers:
// /themes/scriptun/scriptun.theme
function scriptun_theme_suggestions_block_alter(array &$suggestions, array $variables){
if (!empty($variables['elements']['#id'])) {
$block = \Drupal\block\Entity\Block::load($variables['elements']['#id']);
$region = $block->getRegion();
$regionParts = explode('_', $region);
array_pop($regionParts);
if($regionParts){
$suggestions[] = 'block__' . implode('_', $regionParts);
}
// adds suggestion with region and block id
$suggestions[] = 'block__' . $region . '__' . $variables['elements']['#id'];
// adds suggestion with region id
$suggestions[] = 'block__' . $region;
}
}
Add new comment