Get the Symfony route name in a Twig template
Published on 2020-01-09 • Modified on 2020-01-09
Sometimes, it's useful to know the current route name in a Twig template. For example in a layout where you don't "receive" the route name from the controller. It allows setting an "active" class on your menu links depending on the current context. I am using this trick on this website. As you can see, the "snippet" entry of the menu is highlighted. In this case, I test if the current route starts with snippet_
as all routes of this controller start with this string thanks to the route annotation which is set at the class level:
* @Route("/{_locale}/snippets", name="snippet_", requirements={"_locale"="%locales_requirements%"})
<ul>
<li>Current route (short version): <b>{{ app.request.get('_route') }}</b></li>
<li>Current route: <b>{{ app.request.attributes.get('_route') }}</b></li>
</ul>
- Current route (short version): snippet_show
- Current route: snippet_show
More on Stackoverflow Read the doc Random snippet
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉
