criss cross criss cross - 1 month ago 13
PHP Question

Make a link active from the base.html.twig on Navbar in symfony

I researched a lot of things on stack and any other sources.
I found some interesting ideas but couldn't apply them as i'm a student and cannot just yet know where to put things directly in their right spot.

So I got this code right in the base.html.twig

<ul class="nav navbar-nav">
<li class="active">
<a href="{{ path('book_index') }}">Accueil<span class="sr-only">(current)</span></a>
</li>
<li><a href="{{ path('book_ourBooks') }}">Nos livres</a></li>
<li><a href="{{ path('book_aboutUs') }}">Être édité</a></li>
</ul>


and I would like, without using Jquery, being able to show the active when I click on a Link and going to that page.

I found that sort of code :

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


(and other things looking nearly similar)
But I really don't know how and where to put it with my own link and such.
If any help is given, this would be really appreciated, thank you :)

ps: i'm using symfony 2.8

Answer

You need to insert the code on your li's like this:

           <ul class="nav navbar-nav">
                <li class="{% if app.request.attributes.get('_route') == '_RouteName' %}active{% endif %}">
                    <a href="{{ path('book_index') }}">Accueil<span class="sr-only">(current)</span></a>
                </li>
                <li class="{% if app.request.attributes.get('_route') == '_RouteName' %}active{% endif %}">
                 <a href="{{ path('book_ourBooks') }}">Nos livres</a>
                </li>
                <li class="{% if app.request.attributes.get('_route') == '_RouteName' %}active{% endif %}">
                <a href="{{ path('book_aboutUs') }}">Être édité</a>
                </li>
            </ul>

Replace _RouteName with the correct _route for each link.