1

I am trying to make a tag navlink active in for loop django template. Every link is passing id, base on id matching i would like make nav-link active.

This is my Template html page, this is for loop and here i am checking condition to make nav-link active. I am not able to highlight the nav-link.

<ul class="nav nav-pills" role="tablist"> <li class="nav-item"> <a class="nav-link" href="{% url 'core_app:store' 'all' %}">All</a> </li> {% for type in store_type %} {% if type.id == typeid %} <li class="nav-item"> <a class="nav-link active" href="{% url 'core_app:store' type.id %}">{{type.name}}</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'core_app:store' type.id %}">{{type.name}}</a> </li> {% endif %} {% endfor %} </ul> 

This is my View code Here i am getting all store_type and base on link click and passing id and i am extracting type of store. Then i would like to highlight my nav-link active base on conditional matching

def store(request, id): if id == "all": store_list = Store.objects.all().order_by('id') else: store_list = Store.objects.all().filter(store_type=int(id)).order_by('id') return render(request, 'core_app/store/all_store.html', {'stores': store_list, 'typeid': id, "store": "active", 'store_list': 'active', 'store_type': StoreType.objects.all()}) 

Model (Store has StoreType)

class StoreType(models.Model): name = models.CharField(max_length=255, blank=True, null=True) ... def __str__(self): return self.name class Store(model.Model): store_type = models.ForeignKey(...) name = models.CharField(max_length=255, blank=True, null=True) ... 

Please help me to fix this or Suggest me better solution. Thanks

1 Answer 1

0

In your code typeid is a string, while type.id is an integer, just cast it as an integer and it should work:

<ul class="nav nav-pills" role="tablist"> <li class="nav-item"> <a class="nav-link {% if typeid|int == 0 %}active{% endif %}" href="{% url 'core_app:store' 'all' %}">All</a> </li> {% for type in store_type %} {% if type.id == typeid|int %} <li class="nav-item"> <a class="nav-link active" href="{% url 'core_app:store' type.id %}">{{type.name}}</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'core_app:store' type.id %}">{{type.name}}</a> </li> {% endif %} {% endfor %} </ul> 
Sign up to request clarification or add additional context in comments.

1 Comment

oh my bad! thank a lot, i got error (TemplateSyntax error - invalid filter: 'int') using this {% if type.id == typeid|int %} so i changed like this {% if type.id|stringformat:'s' == typeid %}. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.