How to render a tree in Twig

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

    I played around with domi27's idea and came up with this. I made a nested array as my tree, ['link']['sublinks'] is null or another array of more of the same.

    Templates

    The sub-template file to recurse with:

    
    {% for link in links %}
        
  • {{ link.name }} {% if link.sublinks %}
      {% include "includes/menu-links.html" with {'links': link.sublinks} %}
    {% endif %}
  • {% endfor %}

    Then in the main template, call this (kind of redundant 'with' stuff there):

    
    

    Macros

    A similar effect can be achieved with macros:

    
    {% macro menu_links(links) %}
        {% for link in links %}
            
  • {{ link.name }} {% if link.sublinks %}
      {{ _self.menu_links(link.sublinks) }}
    {% endif %}
  • {% endfor %} {% endmacro %}

    In the main template, do this:

    {% import "macros/menu-macros.html" as macros %}
    
    

提交回复
热议问题