php 如何在 TWIG 中获取当前 URL 或路由?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10676218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the current URL or route in TWIG?
提问by MikeGA
I'm very new to Symfony2 and I need to be able to test the current route in TWIG so I can display sub-menus in a template that's rendered like:
我对 Symfony2 非常陌生,我需要能够在 TWIG 中测试当前路线,以便我可以在呈现如下的模板中显示子菜单:
{% render "CPAdminBundle:Messages:sidebarMenu" %}
{% render "CPAdminBundle:Readings:sidebarMenu" %}
Within the sidebar templates I tried using the following but it throws an error:
在侧边栏模板中,我尝试使用以下内容,但会引发错误:
path(app.request.attributes.get('_route'))
What's the correct way of doing what I'm trying to accomplish?
做我想要完成的事情的正确方法是什么?
回答by Samy Dindane
The check you want to do doesn't belong to a view. Views should only take care of displaying, not doing any kind of logic.
您要执行的检查不属于视图。视图应该只负责显示,而不是做任何类型的逻辑。
Do the check in your controller and store it in a variable, pass this variable to your views, and the check the value of this variable in there.
If you want to do this on every action, give the kernel.controller eventa look.
检查您的控制器并将其存储在一个变量中,将此变量传递给您的视图,并在那里检查此变量的值。
如果您想对每个操作都执行此操作,请查看kernel.controller 事件。
If you want to do it in the view anyway, simply compare app.request.attributes.get('_route')to the route you want. I don't understand why you put in path().
如果您无论如何都想在视图中执行此操作,只需与app.request.attributes.get('_route')您想要的路线进行比较即可。我不明白你为什么放进去path()。
{% if app.request.attributes.get('_route') == 'my_route' %}
{% endif %}

