Skip to content

Instantly share code, notes, and snippets.

@whusterj
Created November 18, 2014 23:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whusterj/382399a7a496136c7c00 to your computer and use it in GitHub Desktop.
Save whusterj/382399a7a496136c7c00 to your computer and use it in GitHub Desktop.
Django custom template tag useful for marking navigation links with an 'active' class.
"""
Easily mark navigation links with an 'active' class in Django templates.
Usage::
<a href="{% url 'some_view_name' %}" class="{% active request 'some_view_name' %}">Link to Somewhere</a>
"""
from django.core.urlresolvers import reverse
from django import template
register = template.Library()
@register.simple_tag
def active(request, url_name):
"""Use when adding an 'active' class to navigation links"""
if request.path == reverse(url_name):
return 'active'
return None
@whusterj
Copy link
Author

Example Usage

This tag mirrors the syntax of the built-in {% url %} tag and likewise looks up the path for a given view name. It compares this path with the current request path. If they are equal, it returns an 'active' class.

   <a href="{% url 'some_view_name' %}"
      class="{% active request 'some_view_name' %}">Link to Somewhere</a>

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