如何在Symfony 2中获取当前路由?
例如routing.yml:
somePage:
pattern: /page/
defaults: { _controller: "AcmeBundle:Test:index" }
如何获得这个somePage值?
如何在Symfony 2中获取当前路由?
例如routing.yml:
somePage:
pattern: /page/
defaults: { _controller: "AcmeBundle:Test:index" }
如何获得这个somePage值?
当前回答
在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>
其他回答
不存在适用于所有用例的解决方案。如果您使用$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');
}
如果你在模板中需要它,你可以用它来做一个树枝扩展。
来自ContainerAware(比如控制器):
$request = $this->container->get('request');
$routeName = $request->get('_route');
如果你想在你的控制器中获取路由名,那么你必须注入请求(而不是从容器中获取,因为Symfony UPGRADE,而不是调用get('_route')。
public function indexAction(Request $request)
{
$routeName = $request->get('_route');
}
如果你想在twig中获取路由名,你必须像这样
{{ app.request.attributes.get('_route') }}
我从中得到的只是 _internal
我用$this->getRequest()->get('_route')从控制器内部获得路由名称。 甚至代码tuxedo25也建议返回_internal
这段代码是在Symfony 1.X中所谓的“组件”中执行的;不是页面的控制器,而是页面的一部分,需要一些逻辑。
Symfony 1中的等效代码。X是:sfContext::getInstance()->getRouting()->getCurrentRouteName();
要根据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;
}