0

I need to receive (for example by menu machine name) and operate menu items data to use it in Drupal Twig template like:

<ul>
{% for item in items %}
    <li><a href="{{ item.url }}">{{ item.title }}</a></li>
{% endfor %}
</ul>

But I can't find an information on how to do that.

The only thing I've found is like

{% import _self as menus %}
{{ menus.menu_links(items, attributes, 0) }}
{% macro menu_links(items, attributes, menu_level) %}
...

But I don't understand how to use such code. For example where is menu machine name specified? Can I use it in header.html.twig or only in menu.html.twig? Etc...

4
  • 2
    1) Available variables are ALWAYS limited to their respective Twig template suggestion, you can't get single menu items in e.g. head.html.twig (and this is true for every template and every variable) 2) Read the docs 3) Install Twig Tweak module and then do a {{ dd(_context) }} to perform a var_dump of all available variables in that template.
    – Hudri
    Jul 16 at 10:51
  • 2
    I'll save you the time, you don't need menu machine names in twig because you can create a twig file with a specific naming pattern that will always be used for specific menus by their machine name.
    – Kevin
    Jul 16 at 10:59
  • @Kevin, I've named my template as menu--main.html.twig (main is the machine name of my menu), placed in the file the code from core/modules/system/templates/menu.html.twig and included the file to my header.html.twig. But menu is still not rendered on the page. What's wrong?
    – stckvrw
    Jul 16 at 11:48
  • 2
    As the first comment says you cannot just include template files like that and have it "work". You need to place the menu block into the correct region of your theme to get the menu to render.
    – Kevin
    Jul 16 at 11:58

Your Answer

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

Browse other questions tagged or ask your own question.