In the first look, the process of solving this problem maybe seems very easy, but this problem makes me really confused.
Imagine that I want to have two main-menu one in the header (primary menu/ top bar) and another in the footer region of my site with different style and template.
By default, there is no file suggestion that differentiates which twig file to be used for a menu based on the region.
That's why I follow below article to add block region as the id of main-menu and make block's template name suggestion unique and dedicated for next customization.

Drupal 8: Theming menus by KristianKaa

function THEMENAME_preprocess_block(&$variables) {
  $variables['content']['#attributes']['block'] = $variables['attributes']['id'];

function THEMENAME_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  if (isset($variables['attributes']['block'])) {
    $hook = str_replace(array('block-', '-'), array('', '_'), $variables['attributes']['block']);
    $suggestions[] = $variables['theme_hook_original'] . '__' . $hook;

But the following HTML comments, are the theme hook suggestions added by the debug function, for the Main navigation blocks after adding those codes.

Header section:

   * menu--main.html.twig
   * menu--main--mainnavigation-2.html.twig
   x menu.html.twig

Footer section:

   * menu--main.html.twig
   * menu--main--mainnavigation-2.html.twig
   x menu.html.twig

As you can see from the suggestions, there is nothing to distinguish the two menus from one another based on regions.
I think this template name suggestion hasn't any efficiency in this case because what's that suggested isn't semantic.

So my main question is: How can I add extra filename suggestions for main-menu based on regions not block Id? Or
How to get the current region inside the Hook_theme_suggestions_menu_alter, to add my own suggestion?

I read below posts also but all of those add block Id as twig suggestions for menus:
Additional twig suggestions for menus
How to create a custom Twig Template for Menu Block
How to make a theme hook suggestion for menu according to the region?


You should install the Menu Block module, which will let you dictate the name of the instance of the menu for easy theming. It is then up to you to give it a name.

TBH you don't want to get in the game of trying to manipulate region suggestions based on what it may or may not contain.

enter image description here

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.