5

I want to get the current route on twig , I used this two code but It fail always

Code 1:

 {% if app.request.get('_route') == 'my_route' %}
      //Do something
 {% endif %}

Code 2:

{% if app.request.attributes.get == 'my_route' %}
      //Do something
 {% endif %}
Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
hassen zouari
  • 941
  • 2
  • 11
  • 18

1 Answers1

6

Use the "app_dev.php" at the end of your URL to debug and check what route is being used at the bottom. For example I show "route1" here: Debug showing route1

Then in your twig template you can use something like this:

{% if app.request.attributes.get('_route') == 'route1' %}
    <h1>test</h1>
{% endif %}

I verified this works. I'm using Symfony3 though.

Maybe also try instead of "app.request.attributes.get()", try these:

  • app.request.pathinfo
  • app.request.uri

See if those work.

Also if the route is indeed null, try:

{% if app.request.attributes.get('_route') == '' %}
    <h1>test</h1>
{% endif %}
Alvin Bunk
  • 7,621
  • 3
  • 29
  • 45