Reputation: 1258
I have a Twig template with a simple fixed menu. I use the code below to determine the link that corresponds with the current page. This is far from pretty. Is there an alternative way to determine this in Twig it self?
I prefer not to send an array from the controller to the template where the links are defined (in that way I could check for the current page in the loop and avoid - in my eyes - double code)
Is there something I oversaw in the documentation of Twig?
<ul>
<li {% if app.request.get('_route') == 'all' %}class="current"{% endif %}>
<a href="{{ path('all') }}">All</a>
</li>
<li {% if app.request.get('_route') == 'second' %}class="current"{% endif %}>
<a href="{{ path('second') }}">Second</a>
</li>
<li {% if app.request.get('_route') == 'third' %}class="current"{% endif %}>
<a href="{{ path('third') }}">Third</a>
</li>
<li {% if app.request.get('_route') == 'fourth' %}class="current"{% endif %}>
<a href="{{ path('fourth') }}">Fourth</a>
</li>
</ul>
Upvotes: 2
Views: 1839
Reputation: 712
I actually think this might the best way to do it - at least in terms of accessing app.request.get('_route')
. The only alternative could be app.request.getUri
but that feels less dynamic - that is to say, if the route's URL changed, you'd need to update your template.
You could of course store the current route in a variable that you then passed to the template, which would mean you didn't have to keep accessing app.request.get('_route')
; instead you could just check against that variable each time.
Upvotes: 2