Skip to content

Add tree tag to Twig 4.0 #4144

Description

@tacman

I think the tree tag for recursing data structures where the children have the same structure as the parent nodes is pretty useful.

{% tree item in menu %}
  {% if treeloop.first %}<ul>{% endif %}
    <li>
        <a href="{{ item.url }}">{{ item.name }}</a>
        {% subtree item.children %}
    </li>
  {% if treeloop.last %}</ul>{% endif %}
{% endtree %}

Just like a {% for %} loop, you can access the key of each list item:

{% tree key, item in menu %}
  <li>
    <b>Item {{ key }}</b>: {{ item.name }}
    {% subtree item.children %}
  </li>
{% endtree %}

Since Twig 4 is under development, would you consider adding this extension to the Twig core?

https://github.com/tacman/twig-tree-tag

I can clean up the documentation and such a bit if that helps. I didn't write the original or even the first set of tweaks, but I did get it working with Twig 3 and the dev version of Twig 4.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions