我想在 Twig View 中显示 Symfony 3 中的当前路线。
我已经做了一些研究,但没有找到任何解决方案。我在 Twig View 中尝试以下操作:
{{ 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
这样的 URL,我想检索 /article/5
。如何执行此操作?
最佳答案
下面的代码片段就可以解决这个问题:
{{ 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 }}
关于symfony - 获取 Symfony 3.3 和 Twig 中的当前路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46391808/