0

I'm looking for a possibility of rendering the same menu twice, once on the regular place, and another for mobile on a completely different place in my layout, with a completely different structure.

I was looking at JavaScript, but would rather do it with PHP and Twig

2
  • Why don't you just add the menu block twice on /admin/structure/block? Mar 13, 2016 at 10:37
  • That was my first bet, but the thing is that it's the same menu (same items) but with a different structure, the menu override menu--menuname.html.twig is the same
    – pjcarly
    Mar 13, 2016 at 20:33

2 Answers 2

1

1) Add the menu block a second time (@/admin/structure/block). Give it a specific machine name (eg. main_menu_mobile).

2) Create a second menu template (derived from menu.html.twig) and give it a specific name (eg. menu--main-mobile.html.twig).

3) In your theme, implement a new preprocess hook for blocks and assign another template to your menu:

function mytheme_preprocess_block(&$variables) {
  // Use another template for the main mobile menu.
  if ($variables['elements']['#id'] === 'main_menu_mobile') {
    $variables['content']['#theme'] = 'menu__main_mobile';
  }
}
1
  • It seems good for me. I am implementing this. But i want to know is this a right way to implement menu twice? Or I should follow any other better way? Because if mobile menu disabled from admin, then we would not have mobile menu in pages.
    – siddiq
    Nov 22, 2017 at 3:43
0

I assume you have a custom page-template for your site. And you are using the block-system for rendering your regions. So you may have a region called header with your menu in it.

<div class="regular-menu">
  {{ page.header }}
</div>
<div class="mobile-menu">
  {{ page.header }}
</div>

let me know if I got your question correctly.

4
  • won't work, I need a different structure for my html elements of my mobile menu
    – pjcarly
    Mar 13, 2016 at 20:34
  • Ok so you really want to know how to render your menu with a custom structure and not how to place the drupal-rendered menu twice in your template?
    – Nicensin
    Mar 13, 2016 at 21:04
  • no both, I have a correctly working menu which I need to keep, but I need a second menu, structured and rendered differently for mobile, but with the same menu items from the already rendered menu
    – pjcarly
    Mar 13, 2016 at 21:16
  • If you want to change the structure of your menu you should have a look here: api.drupal.org/api/drupal/… in Drupal 7 I did this once with drupalcontrib.org/api/drupal/… but I am not sure this will work in Drupal 8, too.
    – Nicensin
    Mar 13, 2016 at 21:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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