带有 TWIG 的多级菜单 [英] Multi level menu with TWIG
本文介绍了带有 TWIG 的多级菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
要生成一个简单的菜单,我可以这样做:
To generate a simple menu, I can do:
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
然后:
{% embed '...' with { items: ['Home', 'Articles'] %}
但是如果我想创建无尽深层菜单,我该如何编写 TWIG 代码,例如:
But how do I have to write the TWIG code, if I want to create endless deep menus like:
<ul>
<li>Alpha</li>
<li>Bravo</li>
<ul>
<li>Charlie</li>
<li>Delta</li>
<li>Echo</li>
<ul>
<li>Foxtrott</li>
</ul>
<li>Golf</ul>
</ul>
<li>Hotel</li>
<li>India</li>
</ul>
感谢帮助!
推荐答案
要在 twig
中执行递归,您可以使用 宏的
To perform recursion in twig
you can make use of 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 %}
EDIT 使用简单的数组,不可能将子级嵌套在与父级相同的 中.为此,您需要更改数组,
EDIT With a simple array it's not possible to nest children in the same <li>
as the parent. Herefor you would need to change your array 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 %}
这篇关于带有 TWIG 的多级菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文