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. Active page class for selected menu items by kunitoki 8 months ago
  2. template tag for highlighting currently active page by adunar 4 years, 7 months ago
  3. location context_processor by gsf0 3 years, 9 months ago
  4. Active link by ronnie 1 year, 5 months ago
  5. Menu/navigation bars in a tag by ep 5 years, 10 months ago

Comments

amaozhao (on August 9, 2010):

It is great!

#

mdsol (on September 16, 2010):

Hi. I think this project is great. I am trying to integrate this with django-localeurl.

Does anybody knows how to integrate them?

#

Kayla32Barr (on January 17, 2012):

Do you know that it's correct time to get the loans, which would realize your dreams.

#

(Forgotten your password?)