Last active
June 21, 2024 17:50
-
-
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 )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% 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
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 :)