【问题标题】:Multi level menu with TWIG带有 TWIG 的多级菜单
【发布时间】:2017-08-30 20:01:39
【问题描述】:

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

<ul>
  {% for item in items %}
    <li>{{ item }}</li>
  {% endfor %}
</ul>

然后:

{% embed '...' with { items: ['Home', 'Articles'] %}

但是如果我想创建 endless 深层菜单,我该如何编写 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>

谢谢帮助!

【问题讨论】:

    标签: menu twig


    【解决方案1】:

    要在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 %}
    

    twigfiddle


    EDIT 使用简单的数组,不可能将子级嵌套在与父级相同的&lt;li&gt; 中。为此,您需要更改数组 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 %}
    

    twigfiddle

    【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签