Login

Using URLs for highlighting sections in menu

Author:
diverman
Posted:
August 9, 2010
Language:
Python
Version:
1.2
Score:
3 (after 3 ratings)

Use this, if you want to "activate" menu items by URL. Typical usage is with CSS class 'active'.

 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 - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.