How do I get the current route in Symfony 2?
For example, routing.yml
:
somePage:
pattern: /page/
defaults: { _controller: "AcmeBundle:Test:index" }
How can I get this somePage
value?
How do I get the current route in Symfony 2?
For example, routing.yml
:
somePage:
pattern: /page/
defaults: { _controller: "AcmeBundle:Test:index" }
How can I get this somePage
value?
_route
is not the way to go and never was. It was always meant for debugging purposes according to Fabien who created Symfony. It is unreliable as it will not work with things like forwarding and other direct calls to controllers like partial rendering.You need to inject your route's name as a parameter in your controller, see the doc here
Also, please never use
$request->get('');
if you do not need the flexibility it is way slower than using get on the specific property bag that you need (attributes, query or request) so$request->attributes->get('_route');
in this case.For anybody that need current route for Symfony 3, this is what I use
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:
You can make a twig extension out of this if you need it in templates.
if you want to get route name in your controller than you have to inject the request (instead of getting from container due to Symfony UPGRADE and than call get('_route').
if you want to get route name in twig than you have to get it like
Symfony 2.0-2.1
Use this:
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
And your controller:
To get the current route based on the URL (more reliable in case of forwards):