Drupal core uses the same TWIG template for all instances of a menu. bummer.
Luckily, KristianKaa added this neat piece of code:
/**
* Implements hook_preprocess_block().
*/
function mymodule_preprocess_block(&$variables) {
$variables['content']['#attributes']['block'] = $variables['attributes']['id'];
}/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function mymodule_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
// Remove the block and replace dashes with underscores in the block ID to
// use for the hook name.
if (isset($variables['attributes']['block'])) {
$hook = str_replace(array('block-', '-'), array('', '_'), $variables['attributes']['block']);
$suggestions[] = $variables['theme_hook_original'] . '__' . $hook;
}
}
http://kristiankaa.dk/article/drupal8-region-specific-menu-theme-hook-suggestion
thank you KristianKaa
UPDATE:
I think templates should be more flexible, so I also integrated this:
https://www.drupal.org/forum/support/theme-development/2017-07-13/extra-template-name-suggestions-for-main-menus-based-on
final product: templates can be based on theme regions, block names or both:
<?php
/**
* Implements hook_preprocess_block().
*/
function drupal8_w3css_subtheme_preprocess_block(&$variables) {
$variables['content']['#attributes']['block'] = $variables['attributes']['id'];
}
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function drupal8_w3css_subtheme_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
// Remove the block and replace dashes with underscores in the block ID to
// use for the hook name.
if (isset($variables['attributes']['block'])) {
$hook = str_replace(array('block-', '-'), array('', '_'), $variables['attributes']['block']);
$block = \Drupal\block\Entity\Block::load($hook);
$region = $block->getRegion();
$suggestions[] = $variables['theme_hook_original'] . '__' . $region . '__' . $hook;
$suggestions[] = $variables['theme_hook_original'] . '__' . $hook;
$suggestions[] = $variables['theme_hook_original'] . '__' . $region;
}
}
- Log in to post comments
Comments