putting active class in django code example
Example 1: bootstrap Navbar active in django
'''We will pass a unique variable for each page whose value will be 'active' to make
a page active in navbar when it call.'''
def index(request):
context = {"home_page": "active"}
return render(request, 'pages/index.html', context)
def about(request):
context = {"about_page": "active"}
return render(request, 'pages/about.html', context)
def contact(request):
context = {"contact_page": "active"}
return render(request, 'pages/contact.html', context)
'''
<ul class="navbar-nav">
<li class="nav-item {{ home_page }}">
<a class="nav-link" href="{% url 'index' %}">Home</a>
</li>
<li class="nav-item {{ about_page }}">
<a class="nav-link" href="{% url 'about' %}">About</a>
</li>
<li class="nav-item {{ contact_page }}">
<a class="nav-link" href="{% url 'contact' %}">Contact</a>
</li>
</ul>
'''
Example 2: how to add an active class to current element in navbar in django
<li {% if request.resolver_match.url_name == 'home' %}class="active"{% endif %}>
<a href="/">HOME</a>
</li>