获取当前路线树枝

has*_*ari 3 symfony twig

我想在树枝上获取当前路线,我使用了这两个代码,但总是失败

代码1:

 {% if app.request.get('_route') == 'my_route' %}
      //Do something
 {% endif %}
Run Code Online (Sandbox Code Playgroud)

代码2:

{% if app.request.attributes.get == 'my_route' %}
      //Do something
 {% endif %}
Run Code Online (Sandbox Code Playgroud)

Alv*_*unk 5

使用URL末尾的“ app_dev.php”进行调试,并检查底部使用的路由。例如,我在这里显示“ route1”: 调试显示route1

然后,在您的树枝模板中,您可以使用以下内容:

{% if app.request.attributes.get('_route') == 'route1' %}
    <h1>test</h1>
{% endif %}
Run Code Online (Sandbox Code Playgroud)

我验证了这项工作。我虽然在用Symfony3。

也许也尝试代替“ app.request.attributes.get()”,尝试以下方法:

  • app.request.pathinfo
  • app.request.uri

看看那些工作。

另外,如果路由确实为null,请尝试:

{% if app.request.attributes.get('_route') == '' %}
    <h1>test</h1>
{% endif %}
Run Code Online (Sandbox Code Playgroud)