Skip to content

Instantly share code, notes, and snippets.

@imago-storm
Forked from isthatcentered/recursive_list.twig
Created May 14, 2019 13:32
Show Gist options
  • Save imago-storm/02a699bf3aa07679b0067c9cd0a75e2e to your computer and use it in GitHub Desktop.
Save imago-storm/02a699bf3aa07679b0067c9cd0a75e2e 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 %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment