2017-09-24 70 views
0

我想在Twig视图中使用Symfony 3中的当前路由。在Symfony 3.3和Twig中获取当前路由

我已经做了一些研究,但没有找到任何解决方案。我尝试在我的嫩枝观点如下:

{{ app.request.uri }} 

它返回类似:http://localhost:8000/_fragment?_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3DFOSUserBundle%253ASecurity%253Alogin

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

始终返回NULL。

{{ app.request.getpathinfo }} 

总是有:/_fragment

我需要的是非常简单的。对于像localhost:8000/article/5这样的网址,我想检索/article/5。如何执行此操作?

回答

0

下面的代码片段将这样的伎俩:

{{ path(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')) }} 

app.request.attributes.get('_route') - 返回当前路径名。

app.request.attributes.get('_route_params') - 返回当前路径参数。

path() - 通过路由名称和参数生成路由路径。

这种方法不适用于转发的请求。如果有前向请求,则有workaround:您应该将“_route”和“_route_params”传递给转发的参数列表。你

return $this->forward('Yourbundle:Controller:action', array(
    //... your parameters..., 
    '_route' => $this->getRequest()->attributes->get('_route'), 
    '_route_params' => $this->getRequest()->attributes->get('_route_params'); 
)); 

也可以使用app.request访问任何Request对象的功能,如getPathInfo(),它应该返回当前路由路径。

{{ app.request.pathInfo }} 
+1

谢谢,但我读了几个消息来源说''app.request.get('_ route')'仅用于调试目的,并且可能会很慢。 与app.request.attributes.get('_ route')'是一样的吗? 今天这个问题仍然有关吗? – Arphel

+0

“app.request”是指一个Request对象,它被设计用于你的应用程序的任何部分(在任何环境中)来访问与请求相关的信息,而不是使用PHP全局变量。 –

+0

更新了我的回答,并提供了解决转发请求问题的方法。 –