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)
美丽,不是吗?
小智 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)
这是我使用的(Symfony 5):
<li class="nav-item{% if (app.request.pathInfo == path('frontend_index')) %} active{% endif %}">
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10953 次 |
| 最近记录: |