如何在Symfony 2中获取当前路由?

例如routing.yml:

somePage:
   pattern: /page/
   defaults: { _controller: "AcmeBundle:Test:index" }

如何获得这个somePage值?


当前回答

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

您可以从控制器内的请求对象中获取路由名称。

其他回答

来自ContainerAware(比如控制器):

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

您可以从控制器内的请求对象中获取路由名称。

对于任何需要Symfony 3当前路由的人,这是我使用的

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

要根据URL获取当前路由(在转发的情况下更可靠):

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;
}

_route不是我们要走的路,从来都不是。根据创建Symfony的Fabien的说法,它总是用于调试目的。它是不可靠的,因为它不能用于转发和其他对控制器的直接调用,如部分呈现。

你需要在你的控制器中注入你的路由名作为参数,请看这里的文档

另外,请永远不要使用$request->get(");如果你不需要灵活性,它比使用特定的属性包,你需要(属性,查询或请求)慢得多,所以$request->属性->get('_route');在这种情况下。