我的路线是
admin:
path: /admin/
defaults: { _controller: CatalogWebBundle:Admin:admin }
如何在 PHP 模板中获取路由名称?
最佳答案
获取当前网址
$request->getRequestUri();
或 app.request.uri
至于路由本身,最好的做法是将它作为参数注入(inject)到你的 Controller 中,参见the doc here .您可以使用 $request->attributes->get('_route')
或 app.request.attributes.get('_route')
但它不那么可靠,例如它 won't work with forwards当您转发到 Controller 而不是路径时。而且真的只有meant for debugging purposes according to Fabien (@fabpot), the creator ,所以为了将来的升级我不会依赖它。
旁注
记得给avoid $request->get()
任何时候都可以,所以没有 $request->get('_route')
正如我在类似问题的一些答案中看到的那样
If you don't need the flexibility in controllers, it is better to explicitly get request parameters from the appropriate public property instead (attributes, query, request)
原因是它会查看所述公共(public)属性(属性、查询和请求),而不仅仅是一个(属性),这使得速度慢得多
关于php - Symfony2 - 获取 TWIG 模板中的当前 URL 或路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28913347/