Skip to content

Instantly share code, notes, and snippets.

@edgabaldi
Forked from elyezer/navigation.py
Created November 12, 2012 11:43
Show Gist options
  • Save edgabaldi/4058886 to your computer and use it in GitHub Desktop.
Save edgabaldi/4058886 to your computer and use it in GitHub Desktop.
Template tag to add active class in navigation links
<!-- Specific path, only when visiting /accounts/ -->
<li class="{% active request "^/accounts/$" %}"><a href="/accounts/">Accounts</a></li>
<!-- Glob path, when visiting /blog/* example /blog/, /blog/post1/, /blog/post2/, /blog/post2/subitem/, ... -->
<li class="{% active request "^/blog/" %}"><a href="/blog/">Blog</a></li>
from django import template
register = template.Library()
@register.simple_tag
def active(request, pattern):
import re
if re.search(pattern, request.path):
return 'active'
return ''
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
# Other settings...
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
)
# Other settings...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment