Skip to content

Instantly share code, notes, and snippets.

@pylemon
Forked from mnazim/active_tag.py
Created September 25, 2012 02:15
Show Gist options
  • Save pylemon/3779586 to your computer and use it in GitHub Desktop.
Save pylemon/3779586 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment