带TWIG的多级菜单

Sup*_* 64 1 menu twig

要生成一个简单的菜单,我可以这样做:

<ul>
  {% for item in items %}
    <li>{{ item }}</li>
  {% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)

然后:

{% embed '...' with { items: ['Home', 'Articles'] %}
Run Code Online (Sandbox Code Playgroud)

但是,如果我想创建无穷无尽的深层菜单,我该如何编写TWIG代码:

<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>
Run Code Online (Sandbox Code Playgroud)

求救!

Dar*_*Bee 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 %}
Run Code Online (Sandbox Code Playgroud)

twigfiddle


编辑使用简单数组,不可能将子项<li>与父项嵌套在一起.因此,您需要更改数组arround,

Reformed array

$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'  => [],
                        ],                      
                    ],
                ],              
            ],
        ],      
    ]   
];
Run Code Online (Sandbox Code Playgroud)

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 %}
Run Code Online (Sandbox Code Playgroud)

twigfiddle