要生成一个简单的菜单,我可以这样做:
plt.show()
然后:
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
但是,如果我想创建无尽的深层菜单,我该如何编写TWIG代码:
{% embed '...' with { items: ['Home', 'Articles'] %}
寻求帮助!
答案 0 :(得分:5)
要在twig
中执行递归,您可以使用macro's
{% import _self as macro %}
{{ macro.multilevel(foo) }}
{% macro multilevel(array) %}
{% import _self as macro %}
<ul>
{% for item in array %}
<li>
{% if item is iterable %}
{{ macro.multilevel(item) }}
{% else %}
{{ item }}
{% endif %}
</li>
{% endfor %}
</ul>
{% endmacro %}
编辑使用简单数组,无法将子项嵌套在与父项相同的<li>
中。因此,您需要更改数组arround,
改革后的数组
$data = [
'links' => [
[
'title' => 'alpha',
'href' => 'http://www.alpha.com',
'children' => [],
],
[
'title' => 'beta',
'href' => 'http://www.beta.com',
'children' => [
[
'title' => 'charlie',
'href' => 'http://www.charlie.com',
'children' => [],
],
[
'title' => 'delta',
'href' => 'http://www.delta.com',
'children' => [],
],
[
'title' => 'echo',
'href' => 'http://www.echo.com',
'children' => [
[
'title' => 'foxtrot',
'href' => 'http://www.foxtrot.com',
'children' => [],
],
],
],
],
],
]
];
tiwg
{% macro menu(links) %}
{% import _self as macro %}
<ul>
{% for link in links %}
<li>
<a href="{{ link['href'] }}">{{ link['title'] }}</a>
{% if not link['children']|default([]) is empty %}
{{ macro.menu(link['children']) }}
{% endif %}
</li>
{% endfor %}
</ul>
{% endmacro %}