add active class to link with sf2 and twig

choise picture choise · Apr 17, 2011 · Viewed 46.7k times · Source

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

Answer

Brian picture Brian · Apr 18, 2011

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