hassen zouari
hassen zouari

Reputation: 971

Getting current route twig

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 %}

Upvotes: 5

Views: 5947

Answers (1)

Alvin Bunk
Alvin Bunk

Reputation: 7764

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 %}

Upvotes: 6

Related Questions