Skip to main content

Drupal 8 - add theme suggestion for a block with region id

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

CAPTCHA

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

We use cookies on our website to enhance your user experience. We also use Google analytics and ads.

Click here to read more I've read it