Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add active class to link with sf2 and twig

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

like image 282
choise Avatar asked Apr 17 '11 21:04

choise


4 Answers

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' }}"
like image 188
Brian Avatar answered Oct 09 '22 05:10

Brian


Sometimes you don't want to do exact matching of a route. For those cases, you can use the "starts with" conditional logic of twig.

As an example, lets assume you are working with books. You have the following routes: book, book_show, book_new, book_edit. You want the navigation item Book to be highlighted for any of those cases. This code would accomplish that.

<a class="{% if app.request.attributes.get('_route') starts with 'book' %}active{% endif %}">Books</a>
<a class="{% if app.request.attributes.get('_route') starts with 'author' %}active{% endif %}">Authors</a>

This example works with at least Symfony 2.3.x

like image 35
John Kramlich Avatar answered Oct 09 '22 05:10

John Kramlich


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>
like image 23
Max Lipsky Avatar answered Oct 09 '22 05:10

Max Lipsky


With ternary operator:

    {% set route = app.request.attributes.get('_route') %}
    <ul class="nav navbar-nav">
        <li {{ route ==  'profile_index' ? 'class="active"' }}><a href="{{ path('profile_index') }}"><i class="icon-profile position-left"></i> My Profile</a></li>
        <li {{ route ==  'influencers_index' ? 'class="active"'}}><a href="{{ path('influencers_index') }}"><i class="icon-crown position-left"></i> Influencers</a></li>
        <li {{ route ==  'task_manager_index' ? 'class="active"'}}><a href="{{ path('task_manager_index') }}"><i class="icon-alarm-check position-left"></i> Task Manager</a></li>
    </ul>
like image 10
Yuriy Korman Avatar answered Oct 09 '22 04:10

Yuriy Korman