I would like to render a tree with an undetermined depth (children of children of children, etc.). I need to loop through the array recursively; how can I do this 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:
{% for link in links %}
-
{{ link.name }}
{% if link.sublinks %}
{% include "includes/menu-links.html" with {'links': link.sublinks} %}
{% endif %}
{% endfor %}
Then in the main template, call this (kind of redundant 'with' stuff there):
Macros
A similar effect can be achieved with macros:
{% macro menu_links(links) %}
{% for link in links %}
-
{{ link.name }}
{% if link.sublinks %}
{{ _self.menu_links(link.sublinks) }}
{% endif %}
{% endfor %}
{% endmacro %}
In the main template, do this:
{% import "macros/menu-macros.html" as macros %}