add active class to link with sf2 and twig

前端 未结 10 915
故里飘歌
故里飘歌 2020-12-23 13:48

following simple code:

  • List
  • is there a simple way to add an cl

    10条回答
    •  情书的邮戳
      2020-12-23 14:42

      Twig allows for conditionals and the Request object is available throughout the application. If you are including the template, to get the route you want to use:

      app.request.attributes.get('_route')
      

      If you are using the render function, you want to use:

      app.request.attributes.get('_internal')
      

      With that, you should be able to use:

      class="{% if app.request.attributes.get('_route') == '_list' %}active{% endif %}"
      

      or shorter:

      class="{{ app.request.get('_route') == '_list' ? 'active' }}"
      

    提交回复
    热议问题