0

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

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.

| improve this answer | |
  • This is super helpful Gustavo. Thank you! The super deep menu is actually for an accordion style off-canvas mobile nav as yes, this indeed would get quite unwieldy going that deep! I'll give this a shot and report back if I can answer my own question. Thanks again! – Brian Larson May 30 '17 at 21:06

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.