Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active tag on Bootstrap with Django

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?

like image 605
bryan.blackbee Avatar asked Oct 04 '15 08:10

bryan.blackbee


2 Answers

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>
like image 146
nima Avatar answered Sep 23 '22 00:09

nima


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 %}
like image 20
Kotlinboy Avatar answered Sep 24 '22 00:09

Kotlinboy