For example, Imagine that I designed two main-menu
with different style and template one for the header region (top bar, primary menu section)
and another for the footer region as a "footer map" on my site as it's common in the most sites.
Since Drupal 8 it's not possible with template naming conventions to load a specific block template according to the region it is placed in ("Per-region block markup and per-region block templating feature removed").
In Drupal 7 it was possible to specify separate block templates per region, such as block--header.tpl.php and block--footer.php to output different HTML for blocks placed in the header and footer regions. It was also possible to adjust variables based on the region in hook_preprocess_block(). Both of these features have been removed.
I decide to use below code, by using the below code I can add block region and id to the block template name suggestion:
function MYTHEME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
if (!empty($variables['elements']['#id'])) {
$block = Block::load($variables['elements']['#id']);
$suggestions[] = 'block__' . $block->getRegion() . '__' . $variables['elements']['#id'];
}
If I have considered tree or even more footer region in my theme then my theme users should have this freedom to change the order
of displaying this designed footer menu independent of which sub-footer region that's inserted in;
It is more useful if we design in LTR languages (Like English) and RTL languages(Like Persian)Simultaneously.
But what's that become outputted from above code is something like this:
block--footer-1--mainnavigation-2.html.twig
I think it's a good idea to design the different menu with different semantic name template separately.
It's quite obvious if I need multi instances of a block then Its must probably be in different region, therefore, this difference in positioning make a good and sufficient semantic name convention to assign name to templates and get rid of complication.
for this reason, I want to remove the numbers from the end of block identifier because I think this is very dedicated and I want to achieve something like this:
block--footer--mainnavigation.html.twig
Something else that I want to pay attention to it is if I choose another footer names for example:
footer_menue
instead of footer_1
then this hasn't necessary dynamics in theme layer due to the above reasons.
Anyway, the name convention that I like and follow out is:
What's this?(Most common part) it's block or page or....
Where should be placed? header, footer....
What is his name or usage? main-menu, Search Block,...
Like:Block
+Region Name without Number
+ Block(id) name without number
$suggestions[] = 'block__' . explode('-', $block->getRegion())[0]
.. very very simple example. You have to check the content first of course.preg_replace('[^a-zA-Z]', '', $block->getRegion())