Symfony2 - Get the current URL or route in TWIG template?

To get the current URL

$request->getRequestUri(); or app.request.uri

As for the route itself, the best practice is to inject it as parameter in your controller, see the doc here. You could use $request->attributes->get('_route') or app.request.attributes.get('_route') but it is not as reliable, for example it won't work with forwards as you are forwarding to a controller, not to a path. And it is really only meant for debugging purposes according to Fabien (@fabpot), the creator, so I would not rely on it for future upgrades' sake.

Sidenote

Remember to avoid $request->get() anytime you can, so no $request->get('_route') as I've seen in some answers on similar questions

If you don't need the flexibility in controllers, it is better to explicitly get request parameters from the appropriate public property instead (attributes, query, request)

The reason being that it will look in said public properties (attributes, query & request) instead of just the one (attributes), making it much slower


To get the Route Name in Symfony2 enter the following code snippet

$request = $this->container->get('request');
$routeName = $request->get('_route');

To get the URL in Symfony2,

$request = $this->container->get('request');
$routeURL = $request->getRequestUri();

Not a good thing to do directly in Twig but you can still do. The better way is to pass it as an argument from the controller.

Get route parameters in Twig.

{{ app.request.attributes.get('_route_params') }}

AND

Gets whole bundle name in Twig.

{{ app.request.attributes.get("_controller") }}

Get route name in Twig.

{{ app.request.attributes.get('_route') }}

Tags:

Php

Twig

Symfony