Active class for navigation link

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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: <a class="{% navclass leftnav curentnav name1,name2 %}" href="/about/">
        
    """
    
    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)

More like this

  1. template tag for highlighting currently active page by adunar 5 years, 5 months ago
  2. Active link by ronnie 2 years, 4 months ago
  3. Simple templatetag to mark navigation as active using view names or regex by gluchet 10 months, 4 weeks ago
  4. Using URLs for highlighting sections in menu by diverman 3 years, 8 months ago
  5. Link TemplateTag that checks for permissions and url address by mlouro 4 years, 11 months ago

Comments

(Forgotten your password?)