Make clicked tab active in Bootstrap
If you dont want to send any additional context from views then you can handle it like this with resolver_match:
<li {% if request.resolver_match.url_name == 'home' %}class="active"{% endif %}>
<a href="/">HOME</a>
</li>
where 'home' is the name given to your url pattern for / (probably '^$'
) in your urls.py.
So obviously to use this you need to name all your url patterns, which is a good practice anyway.
This solution didn't work when the href attribute of your links will be different from href="#"
. Why ? Simply because each click on a link triggers a request to the server. In your JS code, you add the method preventDefault() in order to avoid this basic behavior, but I think that not really your objective for this purpose, isn't it ?
To handle this kind of feature you can update your template code by adding something like this :
base.html
<div class="collapse navbar-collapse" id="tn-navbar-collapse">
<ul class="nav navbar-nav">
<li class="{% if nbar == 'home' %}active{% endif %}">
<a href="/">HOME</a>
</li>
...
</ul>
</div>
views.py
def your_view(request):
...
return render(request, 'yourtemplate.html', {'nbar': 'home'})
With this way, you don't have to manage this feature with javascript.