Skip to content

Instantly share code, notes, and snippets.

@elyezer
Last active October 12, 2015 16:58
Show Gist options
  • Save elyezer/4058848 to your computer and use it in GitHub Desktop.
Save elyezer/4058848 to your computer and use it in GitHub Desktop.
Django template tag to add active class in navigation links
{% load navigation %}
<!-- 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