add active class to link with sf2 and twig

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

following simple code:

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

    相关标签:
    10条回答
    • 2020-12-23 14:30

      class="class_name {% if loop.index0 == 0 %}CLASSNAME{% endif %}"

      0 讨论(0)
    • 2020-12-23 14:31

      SF2.2

      {{ dump(app.request.server.get('PATH_INFO')) }}
      
      0 讨论(0)
    • 2020-12-23 14:32

      With ternary operator:

          {% set route = app.request.attributes.get('_route') %}
          <ul class="nav navbar-nav">
              <li {{ route ==  'profile_index' ? 'class="active"' }}><a href="{{ path('profile_index') }}"><i class="icon-profile position-left"></i> My Profile</a></li>
              <li {{ route ==  'influencers_index' ? 'class="active"'}}><a href="{{ path('influencers_index') }}"><i class="icon-crown position-left"></i> Influencers</a></li>
              <li {{ route ==  'task_manager_index' ? 'class="active"'}}><a href="{{ path('task_manager_index') }}"><i class="icon-alarm-check position-left"></i> Task Manager</a></li>
          </ul>
      
      0 讨论(0)
    • 2020-12-23 14:32

      i found a very good Bundle that handles all this stuff automagically:

      https://github.com/KnpLabs/KnpMenuBundle

      0 讨论(0)
    • 2020-12-23 14:34

      Symfony2.3, in Twig, try this to get uri:

      {{ dump(app.request.server.get("REQUEST_URI")) }}
      
      0 讨论(0)
    • 2020-12-23 14:35

      This is how I do it (using Symfony 2.6)

      <li {% if app.request.get('_route') == '_homepage' %} class="active" {% endif %}><a href="{{ path('_homepage') }}">Student</a></li>
      

      '_homepage' is the name of route in routing.yml of your bundle and the route looks like this

      _homepage:
          path:     /
          defaults: { _controller: CoreBundle:Default:index }
      
      0 讨论(0)
    提交回复
    热议问题