我想获取twig上的当前路线,我使用了这两个代码,但总是失败
代码1:
{% if app.request.get('_route') == 'my_route' %}
//Do something
{% endif %}
代码2:
{% if app.request.attributes.get == 'my_route' %}
//Do something
{% endif %}
最佳答案
使用 URL 末尾的“app_dev.php”来调试并检查底部使用的路由。例如我在这里显示“route1”:
然后在你的 Twig 模板中你可以使用这样的东西:
{% if app.request.attributes.get('_route') == 'route1' %}
<h1>test</h1>
{% endif %}
我验证了这个有效。不过我正在使用 Symfony3。
也许也可以尝试代替“app.request.attributes.get()”,尝试以下操作:
- app.request.pathinfo
- app.request.uri
看看这些是否有效。
此外,如果路线确实null,请尝试:
{% if app.request.attributes.get('_route') == '' %}
<h1>test</h1>
{% endif %}
关于symfony - 获取当前路线 Twig ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37502945/