[php] How to get current route in Symfony 2?

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?

This question is related to php symfony routing symfony-routing

The answer is


$request->attributes->get('_route');

You can get the route name from the request object from within the controller.


With Symfony 3.3, I have used this method and working fine.

I have 4 routes like

admin_category_index, admin_category_detail, admin_category_create, admin_category_update

And just one line make an active class for all routes.

<li  {% if app.request.get('_route') starts with 'admin_category' %} class="active"{% endif %}>
 <a href="{{ path('admin_category_index') }}">Product Categoires</a>
</li>

_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.


All I'm getting from that is _internal

I get the route name from inside a controller with $this->getRequest()->get('_route'). Even the code tuxedo25 suggested returns _internal

This code is executed in what was called a 'Component' in Symfony 1.X; Not a page's controller but part of a page which needs some logic.

The equivalent code in Symfony 1.X is: sfContext::getInstance()->getRouting()->getCurrentRouteName();


For anybody that need current route for Symfony 3, this is what I use

<?php
   $request = $this->container->get('router.request_context');
   //Assuming you are on user registration page like https://www.yoursite.com/user/registration
   $scheme = $request->getScheme(); //This will return https
   $host = $request->getHost(); // This will return www.yoursite.com
   $route = $request->getPathInfo(); // This will return user/registration(don't forget this is registrationAction in userController
   $name = $request->get('_route'); // This will return the name.
?>

To get the current route based on the URL (more reliable in case of forwards):

public function getCurrentRoute(Request $request)
{
    $pathInfo    = $request->getPathInfo();
    $routeParams = $this->router->match($pathInfo);
    $routeName   = $routeParams['_route'];
    if (substr($routeName, 0, 1) === '_') {
        return;
    }
    unset($routeParams['_route']);

    $data = [
        'name'   => $routeName,
        'params' => $routeParams,
    ];

    return $data;
}

I think this is the easiest way to do this:

class MyController extends Controller
{
    public function myAction($_route)
    {
        var_dump($_route);
    }

    .....

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').

public function indexAction(Request $request)
{
    $routeName = $request->get('_route');
}

if you want to get route name in twig than you have to get it like

{{ app.request.attributes.get('_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) { ... }

With Twig : {{ app.request.attributes.get('_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.


With Symfony 4.2.7, I'm able to implement the following in my twig template, which displays the custom route name I defined in my controller(s).

In index.html.twig

<div class="col">
    {% set current_path =  app.request.get('_route') %}
    {{ current_path }}
</div>

In my controller


    ...

    class ArticleController extends AbstractController {
        /**
         * @Route("/", name="article_list")
         * @Method({"GET"})
         */
        public function index() {
        ...
        }

        ...
     }

The result prints out "article_list" to the desired page in my browser.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to symfony

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2 The CSRF token is invalid. Please try to resubmit the form What is the difference between .yaml and .yml extension? How can I use break or continue within for loop in Twig template? Running Composer returns: "Could not open input file: composer.phar" Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings Symfony - generate url with parameter in controller Call PHP function from Twig template

Examples related to routing

Send data through routing paths in Angular Angular2 Routing with Hashtag to page anchor Passive Link in Angular 2 - <a href=""> equivalent laravel throwing MethodNotAllowedHttpException How to use absolute path in twig functions S3 Static Website Hosting Route All Paths to Index.html AngularJS - How can I do a redirect with a full page load? Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id} The requested resource does not support HTTP method 'GET' My Routes are Returning a 404, How can I Fix Them?

Examples related to symfony-routing

Symfony - generate url with parameter in controller How to get current route in Symfony 2?