Reputation: 4477
I have a template that looks like this in my html. It uses the bootstrap classes.
<-- navbar-template.html>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li><a href="/home/">Home</a></li>
<li class='active'><a href="/members/">Members</a></li>
<li><a href="#">Research</a></li>
<li><a href="#">Publications</a></li>
<li><a href="#">Links</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
</ul>
</div>
I like the active class but I need the to change which list object it is based on which page from the navbar django has loaded.
I think you'd like to do something like this in the home.html file
<-- HOME -->
{% include "navbar_template.html" with page="home"} %}
###Do something with {{page}} variable in order to set the home list tag to active.
Do I have to write a crazy amount of if else statements or is there an easier way. Perhaps something with the views.py in django
Upvotes: 2
Views: 4068
Reputation: 2671
A cleaner method would be creating a custom template tag. Something like is_active
:
# Inside custom tag - is_active.py
from django.template import Library
from django.core.urlresolvers import reverse
register = Library()
@register.simple_tag
def is_active(request, url):
# Main idea is to check if the url and the current path is a match
if request.path in reverse(url):
return "active"
return ""
And use it in your templates like this:
# template.html
{% load is_active %}
<li><a href="{% url 'home' %}" class="{% is_active request 'home' %}">Home</a></li>
Upvotes: 3
Reputation: 4512
You can do it like this (example solution I use on my page):
<ul class="sidebar-nav--primary">
{% url 'main:home' as home %}
{% url 'main:work' as work %}
{% url 'main:personal' as personal %}
<li><a href="{{ home }}" {% if request.path == home %}class="active"{% endif %}>Home</a></li>
<li><a href="{{ work }}" {% if request.path == work %}class="active"{% endif %}>Work</a></li>
<li><a href="{{ personal }}" {% if request.path == personal %}class="active"{% endif %}>Personal</a></li>
</ul>
Upvotes: 4