简体   繁体   English

树枝导航宏

[英]Twig Navigation macro

I'm trying to create a nested navigation menu using a PHP array and outputting it using Twig. 我正在尝试使用PHP数组创建嵌套的导航菜单,并使用Twig将其输出。 I'm using Yii2 as the PHP framework. 我正在使用Yii2作为PHP框架。 My goal to achieve two things: 我的目标是实现两件事:

  • Add a .active automatically to the nested/children items (they should be able to be deeper than 2 levels). .active自动添加到嵌套/子项中(它们应能够大于2个级别)。

  • Automatically get the parent slug on the item.url , so you don't need to type it out on every child in the array. 自动在item.url上获取父子弹,因此您无需在数组中的每个子子上键入item.url

Here's the PHP array: 这是PHP数组:

return [
    [
        'label' => 'Home',
        'url' => '/',
    ],
    [
        'label' => 'About',
        'url' => 'about',
        'children' => [
            [
                'label' => 'Secondary 1',
                'url' => 'secondary-1',
            ],
            [
                'label' => 'Secondary 2',
                'url' => 'secondary-2',
            ],
        ],
    ],
    [
        'label' => 'Foo',
        'url' => 'foo',
        'children' => [
            [
                'label' => 'Bar',
                'url' => 'bar',
            ],
        ],
    ],
];

And here's the Twig template code so far: 到目前为止,这是Twig模板代码:

{% macro nav(navigation) %}
    {% import _self as macros %}

    {% for item in navigation %}
        {% set active = app.request.getPathInfo starts with item.url or item.url == '/' and app.request.getPathInfo is empty %}

        <li>
            <a href="{{ baseUrl }}/{{ item.url|trim('/',side='left') }}" {{ active ? 'class="active"' : '' }}>{{ item.label }}</a>
            {% if item.children is iterable %}
                <ul>
                    {{ macros.nav(item.children) }}
                </ul>
            {% endif %}
        </li>

    {% endfor %}
{% endmacro %}

{% import _self as macros %}

<nav id="navigation" class="navigation" role="navigation">
    <div class="container">

        <ul>
            {{ macros.nav(navigation) }}
        </ul>

    </div>
</nav>

In order to get the full URL it is required that you pass your current URL down into the recursion. 为了获得完整的URL,要求您将当前URL向下传递到递归中。

{% macro nav(navigation, parent) %}
    {% import _self as macros %}

    {% for item in navigation %}
        {% set active = app.request.getPathInfo starts with item.url or item.url == '/' and app.request.getPathInfo is empty %}

        <li>
            <a href="http://www.example.com/{{ parent |default('') }}{{ item.url|trim('/') }}" {{ active ? 'class="active"' : '' }}>{{ item.label }}</a>
            {% if not item.children|default([]) is empty %}
                <ul>
                    {{ macros.nav(item.children|default([]), (parent?:'')~item.url~'/') }}
                </ul>
            {% endif %}
        </li>

    {% endfor %}
{% endmacro %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM