How to render a tree in Twig

前端 未结 6 1967
灰色年华
灰色年华 2020-11-30 19:20

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?

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 19:52

    If you're running PHP 5.4 or higher, there is a wonderful new solution (as of May 2016) to this problem by Alain Tiemblo: https://github.com/ninsuo/jordan-tree.

    It's a "tree" tag that serves this exact purpose. Markup would look like this:

    {% tree link in links %}
        {% if treeloop.first %}
      {% endif %}
    • {{ link.name }} {% subtree link.sublinks %}
    • {% if treeloop.last %}
    {% endif %} {% endtree %}

提交回复
热议问题