How to check active accordion based on object id?

Viewed 150

Here {% c_url request 'display' %} this will return either display class or None. if display class return I want to keep accordion collapse open. But this is opening all the collapse.

I want to apply display class to the particular #collapseid only. How can I do it ?

template

 {% for n in navs %}
      <li>
        <a
          data-toggle="collapse"
          class="sub{{n.id}} {% c_url request 'active' %}"
          href="#collapse{{n.id}}"
          aria-expanded="true"
          aria-controls="collapse"
          ><p>
            {{n.title}}
          </p></a
        >
        <div class="collapse{{n.id}} {% c_url request 'display' %}"  id="collapse{{n.id}}">
          <ul class="nav">
          {% for i in n.nav_set.all %}
            ..............

          {% endfor %}
        
          </ul>
        </div>
      </li> 
    {% endfor %}

c_url template tag

@register.simple_tag
def c_url(request, value): 

    if request.resolver_match.url_name in ['url1', 'url2']:
        return value
1 Answers

I can suggest two 'easier' options to do it:

  1. Set active status flag on n in navs in context (in views.py):

     for n in navs:
         if <condition for active>:
             n.active = True
    

    Then in the template:

     {% if n.active %}display{% endif %}
    
  2. Add an additional option to the context for the active collapse id: views.py:

     for n in navs:
         if <condition for active>:
             context['active_id'] = n.id
    

    Then in the template:

     {% if n.id == active_id %}display{% endif %}
    
Related