Score:0

How to receive menu items in Twig template as array/object?

gb flag

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...

ru flag
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](https://twig.symfony.com/doc/2.x/tags/macro.html) 3) Install [Twig Tweak module](https://www.drupal.org/project/twig_tweak) and then do a `{{ dd(_context) }}` to perform a var_dump of all available variables in that template.
Kevin avatar
in flag
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.
stckvrw avatar
gb flag
@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?
Kevin avatar
in flag
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.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.