Skip to content

Instantly share code, notes, and snippets.

@mnazim
Created July 9, 2011 14:59
Show Gist options
  • Save mnazim/1073637 to your computer and use it in GitHub Desktop.
Save mnazim/1073637 to your computer and use it in GitHub Desktop.
(Django) A simple template tag to add an 'active' class to anchor tags
from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag
def add_active(request, name, by_path=False):
""" Return the string 'active' current request.path is same as name
Keyword aruguments:
request -- Django request object
name -- name of the url or the actual path
by_path -- True if name contains a url instead of url name
"""
if by_path:
path = name
else:
path = reverse(name)
if request.path == path:
return ' active '
return ''
{% load active_tag %}
{% comment %} Add active class by url name {% endcomment %}
<a class="{% add_active request 'url_name' %}" href="{% url url_name %}">Cars</a>
{% comment %} Add active class by url path {% endcomment %}
<a class="{% add_active request '/some/django/path' 1 %}" href="{% url url_name %}">Cars</a>
Copy link

ghost commented Jan 18, 2018

Do small modification to your code so it can accept "kwargs" in url

def add_active(request, name, pk='', by_path=False):
          if by_path:
             path = name
          elif group:
             path = reverse(name, kwargs={'pk': pk})
          else :
             path = reverse(name)


          if request.path == path:
              return " active "
 
    return ""

<a class="{% add_active request 'url_name' 'pk' %}" href="{% url url_name pk %}">Cars</a>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment