Navigation active state in Django

Here’s a clean way to display a navigation menu item’s active state in Django.

Wherever the app you’re doing this for is located you’ll have an urls.py. Ensure you have the name set within each url group.

from django.conf.urls import patterns, url
from apps.pages import views

urlpatterns = patterns('',
    url(r'^pages/$', views.pages.index, name='pages.index'),
    url(r'^pages/about$', views.pages.about, name='pages.about'),
)

Next create a directory called templatetags within your app folder.
Add to it a blank __init__.py and nav_active.py, giving it the below content.

from django.core.urlresolvers import resolve
from django.template import Library

register = Library()

@register.simple_tag
def nav_active(request, url):
    """
    In template: {% nav_active request "url_name_here" %}
    """
    url_name = resolve(request.path).url_name
    if url_name == url:
        return "active"
    return ""

# nav_active() will check the web request url_name and compare it 
# to the named url group within urls.py, 
# setting the active class if they match.

Now to finish up, in your template .html file you need to load in the template tag and add it to each navigation item.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*