add active class to link with sf2 and twig(添加活动类以与 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 链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!