Created
July 9, 2011 14:59
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 '' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% 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> |
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
Nowadays you can also use
@register.simple_tag(takes_context=True)
and get the request, via the context.