django how to set a navbar active code example
Example 1: bootstrap Navbar active in django
# navbar_demo/pages/views.py...
'''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"} # new info here
return render(request, 'pages/index.html', context)
def about(request):
context = {"about_page": "active"} # new info here
return render(request, 'pages/about.html', context)
def contact(request):
context = {"contact_page": "active"} # new info here
return render(request, 'pages/contact.html', context)
# In html file #
'''
<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: django how to set a navbar active
<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>