Deeply Nested Menu Loop with Twig using Timber

Using TimberMenu() and I have a menu for mobile that needs to go pretty deep. There must be a better way to write this with twig. Using macros and/or loop.parent or loop.index?

It's basically this loop with one nested loop but I need to go all the way down to a great great grandchild.

ul class="menu primary dropdown float-right" aria-hidden="true" data-dropdown-menu data-hover-delay="0" data-closing-time="0"
    {% for item in primary_menu.get_items %}
        li class="{{ item.class }}"
            a href="{{ item.link }}"{{ item.title }}/a
            {% if item.get_children %}
                ul class="menu"
                    {% for child in item.get_children %}
                        li class="{{ child.class }}"a href="{{ child.link }}"{{ child.title }}/a/li
                    {% endfor %}
                /ul
            {% endif %}
        /li
    {% endfor %}
/ul

Topic loop templates menus Wordpress

Category Web


From a usability point of view, have you considered using some sort of sub-menu (maybe a widget in a sidebar), since navigating that many nested menus might be a bit difficult.

Anyways - back to your question. yes you should use a macro. Here's an example I've used before to generate a 3 level deep bootstrap menu (but it can handle more).

page.php

$context['menu']['header_nav'] = new TimberMenu('Header Nav');
Timber::render('page.twig', $context);

macros/menus.twig

{% macro embedded_list(items) %}
    {% import _self as menus %}
    {% for item in items %}
        <li>
            <a href="{{ item.link }}">{{ item.title }}</a>
            {% if item.has_child_class %}
                <ul>
                    {{ menus.embedded_list(item.get_children) }}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
{% endmacro %}

page.twig

<ul>
  {% import 'macros/menus.twig' as menus %}
  {{ menus.embeddded_list(navs.header_nav.items) }}
</ul>

I got this example from this discussion. Here's a blog post about it as well.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.