Using URLs for highlighting sections in menu

 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
### in context processors ###

from django.core.urlresolvers import reverse, resolve

def get_view(name, *args, **kwargs):
    return resolve(reverse(name, args=args, kwargs=kwargs))[0]

class ActiveMenu(object):
    """ mapping urls to selected menu items """

    url_map = {
        get_view('admin:customer_customer_add'):        'customer',
        get_view('admin:customer_customer_change', 0):  'customer',
        get_view('admin:customer_customer_changelist'): 'customer',

        get_view('admin:product_product_add'):          'product',
        get_view('admin:product_product_change', 0):    'product',
        get_view('admin:product_product_changelist'):   'product',
    }

    def __init__(self, request):
        self.active = self.url_map.get(resolve(request.path)[0])

    def __getattr__(self, name):
        return self.active == name

def menu(request):
    """ enable this context processor in settings.py """
    return { 'menu': ActiveMenu(request) }

### in templatetags ###

@register.simple_tag
def active(menu):
    return u'active' if menu else u''

### in template ###

<a href="{% url admin:customer_customer_add }" class="{% active menu.customer %}">Customer</a>

<a href="{% url admin:product_product_add }" class="{% active menu.product %}">Product</a>

More like this

  1. template tag for highlighting currently active page by adunar 5 years, 5 months ago
  2. DRY menu Custom Template Tag by sergzach 2 years ago
  3. Active page class for selected menu items by kunitoki 1 year, 6 months ago
  4. Active link by ronnie 2 years, 4 months ago
  5. URL Query Parameter Menu by drg006 6 years, 11 months ago

Comments

(Forgotten your password?)