导航,突出显示当前页面

tra*_*mpi 11 symfony twig

我有一个父布局,并从该子站点派生.

父布局有一个导航,每个导航点代表一个子站点.

如何在父布局中突出显示当前查看的子站点?if怎么样?

waw*_*awa 30

我知道这是一个老线程,但你仍然发现它在谷歌的前三名中,所以这里有一点点更新.

使用Symfony创建带有"突出显示类"的导航时,您可以采取不同的方法.

1.检查路线
@Sebastian J建议的那样,您可以检查路线的if else.

<li{% if app.request.get('_route') == 'foo_products_overview' %} class="active"{% endif %}>
Run Code Online (Sandbox Code Playgroud)

问题:它没有得到官方的支持,正如@netmikey所指出的:如何在Symfony 2获得当前路由?

1.1.检查路径数组
我实际上在我的项目中使用它,只需一次调整.我使用in数组函数,以便能够提供多个路由.

<li{% if app.request.attributes.get('_route') in [
    'foo_products_overview',
    'foo_products_detail',
    'foo_products_bar'
] %} class="active"{% endif %}>
Run Code Online (Sandbox Code Playgroud)

1.2.检查路线开始......
第三种方法是@bernland所建议的.让我们想要匹配所有以路线开头的路线foo_products,我们想通过魔法来应用它.

<li{% if app.request.attributes.get( '_route' ) starts with 'foo_products' %} class="active"{% endif %}>
Run Code Online (Sandbox Code Playgroud)

正如我所说,我使用它并且还没有问题.

2.使用捆绑/功能 我确定还有其他捆绑包,但我建议您创建导航:https://github.com/KnpLabs/KnpMenuBundle

3.使用宏 编辑2015年7月
我最喜欢的是使用宏像

{% macro menuItem(name, url, subitems) %}
    {% spaceless %}
        {% set subitems = subitems|default({}) %}
        {% set currentUrl = path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')) %}
        {% set isActive = currentUrl == url %}

        {% for name, suburl in subitems %}
            {% set isActive = not isActive and currentUrl == suburl %}
        {% endfor %}

        <li{% if isActive %} class="is-active"{% endif %}>
            <a href="{{ url }}"{% if subitems|length > 0 %} class="has-sub-menu"{% endif %}>{{ name|trans() }}</a>
            {% if subitems|length > 0 %}
                <ul class="main-sub-menu">
                    {% for name, url in subitems %}
                        {{ _self.menuItem(name, url) }}
                    {% endfor %}
                </ul>
            {% endif %}
        </li>
    {% endspaceless %}
{% endmacro %}
Run Code Online (Sandbox Code Playgroud)

只需在你的twig文件中的某个地方添加此代码(不是在一个{% block %}东西!)
然后你可以像这样对一个项目调用它:

{{ _self.menuItem('FooBar', path('foo_foobar')) }}
Run Code Online (Sandbox Code Playgroud)

或者有子项目的项目:

{{ _self.menuItem('FooBar', path('foo_foobar'), {
    'Foo': path('foo_baz', {slug: 'foo'}),
    "Bar": path('foo_baz', {slug: 'bar'}),
}) }}
Run Code Online (Sandbox Code Playgroud)

美丽,不是吗?

  • 非常好的工作简单快捷! (2认同)

小智 9

可能不是最好的选择,但这里是基于路由名称的Symfony2的一些简单方法:

<ul class="nav">
  <li{% if app.request.get('_route') == '_adminIndex' %} class="active"{% endif %}>
    <a href="{{ path('_adminIndex') }}">Admin Home</a>
  </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

  • 依赖于`request.get('_ route')`不是官方支持的,并不总能给你预期的结果.请参阅另一个问题:http://stackoverflow.com/questions/7096546/how-to-get-current-route-in-symfony-2#comment18258756_7096604 (3认同)

Rok*_*gar 5

这是我使用的(Symfony 5):

<li class="nav-item{% if (app.request.pathInfo == path('frontend_index')) %} active{% endif %}">
Run Code Online (Sandbox Code Playgroud)