I am using Django and integrated Bootstrap with Django. Here is my HTML code for the navigation bar:
After adding gamer's JavaScript into your template code_here , you got to make sure you have the similar settings in your CSS file also, in order to make JavaScript work.
.navbar-nav > li.active > a {
color: #d74b4b;
background: transparent;
border-bottom: none;
}
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.
Alternative including URL namespaces:
<li class="nav-item {% if request.resolver_match.view_name == 'scores:list' %}active{% endif %}">
<a class="nav-link" href="{% url 'scores:list' %}">Scores</a>
</li>
I think the easiest solution is JavaScript / CSS:
Anyway, here is the solution using Jquery. Notice n1,n2
classes in html
In base.html
<nav>
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link n1" href="{% url 'polls:dashboard' %}">
<span data-feather="home"></span>
Dashboard
</a>
</li>
<li class="nav-item">
<a class="nav-link n2" href="{% url 'polls:restaurants' %}">
<span data-feather="file"></span>
Restaurants
</a>
</li>
</ul>
</nav>
<script>
$('nav').find('{% block active_link%}{%endblock%}').addClass('active')
</script>
Then in your dashboard template:
{% block active_link %}.n1{%endblock%}
In your restaurants template:
{% block active_link %}.n2{%endblock%}