Login

Active class for navigation link

Author:
cschand
Posted:
September 14, 2009
Language:
HTML/template
Version:
Not specified
Score:
2 (after 2 ratings)

Active class for navigation link

{% 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/">
 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. Bootstrap Accordian by Netplay4 5 years, 2 months ago
  2. Bootstrap theme for django-endless-pagination? by se210 8 years, 2 months ago
  3. Bootstrap theme for django-endless-pagination? by se210 8 years, 2 months ago
  4. Reusable form template with generic view by roldandvg 8 years, 3 months ago
  5. Pagination Django with Boostrap by guilegarcia 8 years, 5 months ago

Comments

raigu (on April 2, 2015):

Hi!

Thanks for this snippet, helped me a lot.

Unfortunately it does not work when the view function requires parameters.

I fixed it by replacing function render with this:

def render(self, context):
    req = template.resolve_variable('request', context)
    url_name = getattr(req.resolver_match, 'url_name')
    if url_name in self.url_names.split(','):
        return 'active'
    else:
        return ''

:)

raigu

#

Please login first before commenting.