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

例如routing.yml:

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

如何获得这个somePage值?


当前回答

我从中得到的只是 _internal

我用$this->getRequest()->get('_route')从控制器内部获得路由名称。 甚至代码tuxedo25也建议返回_internal

这段代码是在Symfony 1.X中所谓的“组件”中执行的;不是页面的控制器,而是页面的一部分,需要一些逻辑。

Symfony 1中的等效代码。X是:sfContext::getInstance()->getRouting()->getCurrentRouteName();

其他回答

不存在适用于所有用例的解决方案。如果您使用$request->get('_route')方法或其变体,它将返回'_internal'用于转发发生的情况。

如果你需要一个解决方案,即使转发,你必须使用新的RequestStack服务,在2.4到达,但这将打破ESI支持:

$requestStack = $container->get('request_stack');
$masterRequest = $requestStack->getMasterRequest(); // this is the call that breaks ESI
if ($masterRequest) {
    echo $masterRequest->attributes->get('_route');
}

如果你在模板中需要它,你可以用它来做一个树枝扩展。

如果你想在你的控制器中获取路由名,那么你必须注入请求(而不是从容器中获取,因为Symfony UPGRADE,而不是调用get('_route')。

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

如果你想在twig中获取路由名,你必须像这样

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

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

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

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

在Symfony 3.3中,我使用了这种方法,并且运行良好。

我有4条路线

Admin_category_index, admin_category_detail, admin_category_create, admin_category_update

只有一行为所有路由创建了一个活动类。

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

使用Twig: {{app.request.attributes.get('_route')}}