How to render a tree in Twig

I played around with domi27’s idea and came up with this. I made a nested array as my tree, [‘link’][‘sublinks’] is null or another array of more of the same.

Templates

The sub-template file to recurse with:

<!--includes/menu-links.html-->
{% for link in links %}
    <li>
        <a href="https://stackoverflow.com/questions/8326482/{{ link.href }}">{{ link.name }}</a>
        {% if link.sublinks %}
            <ul>
                {% include "includes/menu-links.html" with {'links': link.sublinks} %}
            </ul>
        {% endif %}
    </li>
{% endfor %}

Then in the main template, call this (kind of redundant ‘with’ stuff there):

<ul class="main-menu">
    {% include "includes/menu-links.html" with {'links':links} only %}
</ul>

Macros

A similar effect can be achieved with macros:

<!--macros/menu-macros.html-->
{% macro menu_links(links) %}
    {% for link in links %}
        <li>
            <a href="https://stackoverflow.com/questions/8326482/{{ link.href }}">{{ link.name }}</a>
            {% if link.sublinks %}
                <ul>
                    {{ _self.menu_links(link.sublinks) }}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
{% endmacro %}

In the main template, do this:

{% import "macros/menu-macros.html" as macros %}
<ul class="main-menu">
    {{ macros.menu_links(links) }}
</ul>

Leave a Comment