2

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>
Stefan
  • 1,248
  • 6
  • 23
  • Seems a similar question as http://stackoverflow.com/questions/9378714/get-current-url-in-twig-template. – Armage Jun 30 '15 at 14:53
  • @Armage Not so duplicate as my question is about how to avoid the 'double code' for checking what route equals the current page. The referred link is about getting the url it self. – Stefan Jun 30 '15 at 16:03

1 Answers1

2

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.

d0ug7a5
  • 692
  • 4
  • 7