Skip to content

Instantly share code, notes, and snippets.

@victorono
Created May 27, 2014 18:53
Show Gist options
  • Select an option

  • Save victorono/0af94c7daad9b6b522bb to your computer and use it in GitHub Desktop.

Select an option

Save victorono/0af94c7daad9b6b522bb to your computer and use it in GitHub Desktop.
Mark active menu item django templatetag
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
from django.core import urlresolvers
register = template.Library()
@register.simple_tag(takes_context=True)
def current(context, url_name, return_value=' active', **kwargs):
matches = current_url_equals(context, url_name, **kwargs)
return return_value if matches else ''
def current_url_equals(context, url_name, **kwargs):
resolved = False
try:
resolved = urlresolvers.resolve(context.get('request').path)
except:
pass
matches = resolved and resolved.url_name == url_name
if matches and kwargs:
for key in kwargs:
kwarg = kwargs.get(key)
resolved_kwarg = resolved.kwargs.get(key)
if not resolved_kwarg or kwarg != resolved_kwarg:
return False
return matches
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment