I have a bunch of links on my navbar on Bootstrap
<ul class="nav navbar-nav">
<li ><a href="{% url 'home' %}">Home</a></li>
<li ><a href="{% url 'about' %}">About</a></li>
<li ><a href="{% url 'contact' %}">Contact</a></li>
</ul>
Say I am at the "Home" section, I want to add a <li class="active">
text on Django.
My first instinct is to use the context variable for views.py and do something like
context = { 'section' : 'home' }
and then do the matching of the string
<ul class="nav navbar-nav">
<li {% if section == 'home' %}class="active"{% endif %}><a href="{% url 'home' %}">Home</a></li>
<li {% if section == 'about' %}class="active"{% endif %}><a href="{% url 'about' %}">About</a></li>
<li {% if section == 'contact' %}class="active"{% endif %}><a href="{% url 'contact' %}">Contact</a></li>
</ul>
To me, this seems to violate DRY and so I'm asking the community if there is a sleeker way to represent this?
I prefer checking the URL in template:
<li {% if "/" == request.path %}class="active"{% endif %}><a href="{% url 'home' %}">Home</a></li>
<li {% if 'mypage1' in request.path %}class="active"{% endif %}><a href="{% url 'my_page_1' %}">My Page 1</a></li>
The accepted answer isn't perfect and DRY.
<li {% if 'mypage1' in request.path %}class="active"{% endif %}><a href="{% url 'my_page_1' %}">My Page 1</a></li>
What if you change the URL, you'd have to change it here everytime. What if you forget to do it?
What if you have multiple urls with 'my_page_1' in URL, for example, "127.0.0.7/my_page_2/list/my_my_page_1". But we want only "127.0.0.7/my_my_page_1". In this case both the URLs would be active. We don't want that
You can check if the URL matches using request.resolver_match.url_name
instead.
<li class="nav-item {% if request.resolver_match.url_name == 'index' %}active{% endif %}">
or
{% with url_name=request.resolver_match.url_name %}
<li class="nav-item {% if url_name == 'index' %}active{% endif %}"
<a href="{% url 'index' %}" >Home </a>
</li>
{% endwith %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With