Symfony2 - 在 TWIG 模板中获取当前 URL 或路由? [英] Symfony2 - Get the current URL or route in TWIG template?

查看:24
本文介绍了Symfony2 - 在 TWIG 模板中获取当前 URL 或路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的路线是

admin:
      path:     /admin/
      defaults: { _controller: CatalogWebBundle:Admin:admin }

如何在 PHP 模板中获取路由名称?

How I can get route name in PHP template ?

推荐答案

获取当前 URL

$request->getRequestUri();app.request.uri

至于路由本身,最佳做法是将其作为参数注入控制器,请参阅此处的文档.您可以使用 $request->attributes->get('_route')app.request.attributes.get('_route') 但它不是可靠,例如它不会像您一样使用转发转发到控制器,而不是路径.根据 Fabien (@fabpot) 的说法,它实际上只是 用于调试目的,创作者,所以我不会为了将来的升级而依赖它.

As for the route itself, the best practice is to inject it as parameter in your controller, see the doc here. You could use $request->attributes->get('_route') or app.request.attributes.get('_route') but it is not as reliable, for example it won't work with forwards as you are forwarding to a controller, not to a path. And it is really only meant for debugging purposes according to Fabien (@fabpot), the creator, so I would not rely on it for future upgrades' sake.

旁注

记得避免$request->get() 任何时候都可以,所以没有 $request->get('_route') 就像我在类似问题的一些答案中看到的那样

Remember to avoid $request->get() anytime you can, so no $request->get('_route') as I've seen in some answers on similar questions

如果你不需要控制器的灵活性,最好是从适当的公共属性中显式获取请求参数相反(属性、查询、请求)

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)

原因是它将查看所​​述公共属性(属性、查询和请求)而不是仅查看一个(属性),从而使其速度慢得多

The reason being that it will look in said public properties (attributes, query & request) instead of just the one (attributes), making it much slower

这篇关于Symfony2 - 在 TWIG 模板中获取当前 URL 或路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆