Wessi Wessi - 2 months ago 15
HTML Question

Django: Highlight current page in navbar

In my layout.html (sometimes called base.html) I have a navbar like this:

<li class="dropdown"><a href="{% url 'index' %}" >Home </a></li>
<li class="dropdown"><a href="{% url 'house_list' %}">Your houses</a></li>
<li class="dropdown"><a href="{% url 'agency_list' %}">Agencies</a></li>
<li class="dropdown"><a href="/admin">Admin</a></li>
<li class="dropdown"><a href="{% url 'logout' %}"><i class="fa fa-lock"></i> Log ud</a></li>
<li class="dropdown"><a href="{% url 'login' %}"><i class="fa fa-lock"></i> Log ind</a></li>


I would like to highlight the current page in the navbar which is done by changing
<li class="dropdown">
to
<li class="dropdown active">


Is there a way for Django to insert active for the page the user is on? Any help is much appreciated!

I'm using Django 1.9 and Python 3.5.

Answer

You can get the name of the url (referenced in your urlpatterns). Then set the 'active' class if the url matches.

{% with url_name=request.resolver_match.url_name %}
<li class="dropdown {% if url_name == 'index' %}active{% endif %}"
   <a href="{% url 'index' %}" >Home </a>
</li>
<li>...</li>
{% endwith %}