From something that is ContainerAware (like a controller):
$request = $this->container->get('request');
$routeName = $request->get('_route');
With Twig : {{ app.request.attributes.get('_route') }}
I think this is the easiest way to do this:
class MyController extends Controller
{
public function myAction($_route)
{
var_dump($_route);
}
.....
Symfony 2.0-2.1
Use this:
$router = $this->get("router");
$route = $router->match($this->getRequest()->getPathInfo());
var_dump($route['_route']);
That one will not give you _internal
.
Update for Symfony 2.2+: This is not working starting Symfony 2.2+. I opened a bug and the answer was "by design". If you wish to get the route in a sub-action, you must pass it in as an argument
{{ render(controller('YourBundle:Menu:menu', { '_locale': app.request.locale, 'route': app.request.attributes.get('_route') } )) }}
And your controller:
public function menuAction($route) { ... }
There is no solution that works for all use cases. If you use the $request->get('_route') method, or its variants, it will return '_internal' for cases where forwarding took place.
If you need a solution that works even with forwarding, you have to use the new RequestStack service, that arrived in 2.4, but this will break ESI support:
$requestStack = $container->get('request_stack');
$masterRequest = $requestStack->getMasterRequest(); // this is the call that breaks ESI
if ($masterRequest) {
echo $masterRequest->attributes->get('_route');
}
You can make a twig extension out of this if you need it in templates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With