from django.template import Library, Node, resolve_variable, TemplateSyntaxError from django.core.urlresolvers import reverse register = Library() class NavclassNode(Node): def __init__(self, vars): self.vars = vars def render(self, context): req = resolve_variable('request', context) for var in self.vars[2].split(','): try: if reverse(var) == req.META['PATH_INFO']: return self.vars[1] except: pass return self.vars[0] def navclass(parser, token): """ Set active class for navigation link Usage: {% navclass default current url %} First argument is the default class and second is the current class Third argument is the url name(s) of the page example: """ bits = token.contents.split(' ') if len(bits) < 4: raise TemplateSyntaxError, "'%s' tag requires three arguments" % bits[0] vars = [bit for bit in bits[1:]] return NavclassNode(vars) register.tag('navclass', navclass)