How to render a tree in Twig

前端 未结 6 1977
灰色年华
灰色年华 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:31

    First I thought this may be solved in a straightforward way, but it isn't that easy.

    You need to create logic, maybe with a PHP class method, when to include a Twig subtemplate and when not.

    
    
      {% for key, item in menu %} {# Pseudo Twig code #} {% if item|hassubitem %} {% include "subitem.html.tpl" %} {% else %}
    • {{ item }}
    • {% endif %} {% endfor %}

    So you could use the special Twig loop variable, which is available inside a Twig for loop. But I'm not sure about the scope of this loop variable.

    This and other information are available on Twigs "for" Docu!

提交回复
热议问题