添加活动类以与 sf2 和 twig 链接 [英] add active class to link with sf2 and twig

查看:15
本文介绍了添加活动类以与 sf2 和 twig 链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下简单代码:

<li><a href="{{ path('_list') }}">List</a></li>

如果当前页面与 _list 路由匹配,是否有一种简单的方法可以添加 class="active"?

is there a simple way to add an class="active" if the current page matches the _list route?

使用最新的 PR-Release 的 symfony2 和 twig 作为模板引擎

using the newest PR-Release of symfony2 and twig as template engine

推荐答案

Twig 允许使用条件,并且 Request 对象在整个应用程序中都可用.如果您包含模板,以获取您要使用的路线:

Twig allows for conditionals and the Request object is available throughout the application. If you are including the template, to get the route you want to use:

app.request.attributes.get('_route')

如果你正在使用渲染功能,你想使用:

If you are using the render function, you want to use:

app.request.attributes.get('_internal')

有了它,你应该可以使用:

With that, you should be able to use:

class="{% if app.request.attributes.get('_route') == '_list' %}active{% endif %}"

或更短:

class="{{ app.request.get('_route') == '_list' ? 'active' }}"

这篇关于添加活动类以与 sf2 和 twig 链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆