Skip to content

Instantly share code, notes, and snippets.

@isthatcentered
Last active June 21, 2024 17:50
Show Gist options
  • Save isthatcentered/db005b6e3d76f32c4738ea2748395ba0 to your computer and use it in GitHub Desktop.
Save isthatcentered/db005b6e3d76f32c4738ea2748395ba0 to your computer and use it in GitHub Desktop.
Recursive list template for Twig using recursive macros. Compatible Twig 2.x // for grandpas or hipsters using twig in js (hello friends :D )
{% macro list(items, class) %}
<ul class="{{class}}">
{# Iterating over each direct items #}
{% for item in items %}
<li>
<a href="">{{item.name}}</a>
{# If an item has children #}
{% if item.children %}
{# Re-import the macro #}
{% import _self as recursive %}
{# And use it to iterate over item's children #}
{{ recursive.list(item.children) }}
{% endif %}
</li>
{% endfor %}
</ul>
{% endmacro %}
{# Nav Being the variable passed to the template #}
{% if nav %}
{# importing the macro created earlier #}
{% import _self as tree %}
{# using macro {nameOfImport}.{nameOfMethod}(variable) #}
{{ tree.list(nav.children) }}
{% endif %}
@isthatcentered
Copy link
Author

Note,
in newer versions of twig you can save a few line by switching
{% import _self as recursive %}
{{ recursive.list(item.children) }}
to
{{ _self.list(item.children) }}

That's it :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment