add active class to link with sf2 and twig

2019-01-30 19:22发布

following simple code:

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

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

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

10条回答
爷的心禁止访问
2楼-- · 2019-01-30 19:38

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 %}"

or shorter:

class="{{ app.request.get('_route') == '_list' ? 'active' }}"
查看更多
【Aperson】
3楼-- · 2019-01-30 19:42

Shortest version:

{% set route = app.request.get('_route') %}

 <li class="{{ route starts with 'post' ? 'open' }}"></li>
 <li class="{{ route starts with 'category' ? 'open' }}"></li>

Sometimes useful:

{% set route = app.request.get('_route') %}

<li class="{{ 'post' in route ? 'open' }}"></li>
<li class="{{ 'category' in route ? 'open' }}"></li>
查看更多
该账号已被封号
4楼-- · 2019-01-30 19:44

SF2.2

{{ dump(app.request.server.get('PATH_INFO')) }}
查看更多
做自己的国王
5楼-- · 2019-01-30 19:45

i found a very good Bundle that handles all this stuff automagically:

https://github.com/KnpLabs/KnpMenuBundle

查看更多
叼着烟拽天下
6楼-- · 2019-01-30 19:46

Symfony2.3, in Twig, try this to get uri:

{{ dump(app.request.server.get("REQUEST_URI")) }}
查看更多
可以哭但决不认输i
7楼-- · 2019-01-30 19:46

This is how I do it (using Symfony 2.6)

<li {% if app.request.get('_route') == '_homepage' %} class="active" {% endif %}><a href="{{ path('_homepage') }}">Student</a></li>

'_homepage' is the name of route in routing.yml of your bundle and the route looks like this

_homepage:
    path:     /
    defaults: { _controller: CoreBundle:Default:index }
查看更多
登录 后发表回答