how to add an active class to current element in navbar in django

Solutions on MaxInterview for how to add an active class to current element in navbar in django by the best coders in the world

showing results for - "how to add an active class to current element in navbar in django"
Sofie
15 Oct 2017
1# navbar_demo/pages/views.py... 
2
3'''We will pass a unique variable for each page whose value will be 'active' to make 
4a page active in navbar when it call.'''
5
6def index(request):    
7  context = {"home_page": "active"} # new info here    
8  return render(request, 'pages/index.html', context)
9
10def about(request):    
11  context = {"about_page": "active"} # new info here    
12  return render(request, 'pages/about.html', context)
13
14def contact(request):    
15  context = {"contact_page": "active"} # new info here    
16  return render(request, 'pages/contact.html', context)
17
18# In html file #
19 
20'''  
21<ul class="navbar-nav">
22  <li class="nav-item {{ home_page }}">
23      <a class="nav-link" href="{% url 'index' %}">Home</a>
24   </li>
25   <li class="nav-item {{ about_page }}">
26      <a class="nav-link" href="{% url 'about' %}">About</a>
27    </li>
28   <li class="nav-item {{ contact_page }}">
29       <a class="nav-link" href="{% url 'contact' %}">Contact</a>
30    </li>
31 </ul>
32'''
Nada
30 Jul 2016
1<li {% if request.resolver_match.url_name == 'home' %}class="active"{% endif %}>
2    <a href="/">HOME</a>
3</li>
4