本文介绍了如何在 Twig 中渲染一棵树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想渲染一棵深度不确定的树(孩子的孩子的孩子,等等).我需要递归遍历数组;我怎样才能在 Twig 中做到这一点?
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?
推荐答案
我玩弄了 domi27 的想法 并想出了这个.我创建了一个嵌套数组作为我的树,['link']['sublinks'] 为 null 或另一个相同的数组.
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.
模板
要递归的子模板文件:
<!--includes/menu-links.html-->
{% for link in links %}
<li>
<a href="{{ link.href }}">{{ link.name }}</a>
{% if link.sublinks %}
<ul>
{% include "includes/menu-links.html" with {'links': link.sublinks} %}
</ul>
{% endif %}
</li>
{% endfor %}
然后在主模板中,调用它(那里有一些多余的with"东西):
Then in the main template, call this (kind of redundant 'with' stuff there):
<ul class="main-menu">
{% include "includes/menu-links.html" with {'links':links} only %}
</ul>
宏
使用宏可以达到类似的效果:
A similar effect can be achieved with macros:
<!--macros/menu-macros.html-->
{% macro menu_links(links) %}
{% for link in links %}
<li>
<a href="{{ link.href }}">{{ link.name }}</a>
{% if link.sublinks %}
<ul>
{{ _self.menu_links(link.sublinks) }}
</ul>
{% endif %}
</li>
{% endfor %}
{% endmacro %}
在主模板中,执行以下操作:
In the main template, do this:
{% import "macros/menu-macros.html" as macros %}
<ul class="main-menu">
{{ macros.menu_links(links) }}
</ul>
这篇关于如何在 Twig 中渲染一棵树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!