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