I've seen jpwatts', 110j's, nivhab's & Marcus Whybrow's answers, but they all seem to lack in something: what about the root path ? Why it's always active ?
So I've made an other way, easier, which make the "controller" decides by itself and I think it resolve most of the big problems.
Here is my custom tag:
## myapp_tags.py
@register.simple_tag
def nav_css_class(page_class):
if not page_class:
return ""
else:
return page_class
Then, the "controller" declares CSS classes needed (in fact, the most important is it declares its presence to the template)
## views.py
def ping(request):
context={}
context["nav_ping"] = "active"
return render(request, 'myapp/ping.html',context)
And finally, I render it in my navigation bar:
<!-- sidebar.html -->
{% load myapp_tags %}
...
<a class="{% nav_css_class nav_home %}" href="{% url 'index' %}">
Accueil
</a>
<a class="{% nav_css_class nav_candidats %}" href="{% url 'candidats' %}">
Candidats
</a>
<a class="{% nav_css_class nav_ping %}" href="{% url 'ping' %}">
Ping
</a>
<a class="{% nav_css_class nav_stat %}" href="{% url 'statistiques' %}">
Statistiques
</a>
...
So each page has its own nav_css_class
value to set, and if it's set, the template renders active: no need of request
in template context, no URL parcing and no more problems about multi-URL pages or root page.
<a href="{% url "view:name" %}" {% active_class "view:name" %}>
. You can optionally use it to generate just the" active"
value (by passingFalse
as a second argument to the tag) to append to an existing class attribute, but for most nav links that example is what I use. – orokusaki