Quick-and-dirty decorator for static navigation context

 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
42
43
## helpers.py
# Mark as active helper
def mark_as_active_section(col, current_section):
    def mark_as_active(item, current_section):
        if current_section.startswith(item['id']):
            item['active'] = True
        return item
    return map(lambda i: mark_as_active(i, current_section),col)

# Is section decorator
def is_section(func):
    def section_marker(*args, **kwargs):
        if kwargs['menu']:
            kwargs['menu'] = mark_as_active_section(kwargs['menu'], func.__name__)
        return func(*args, **kwargs)
    return section_marker

## urls.py
# Static Menu
menu = lambda: [
    {'id':'home','title':'Home','active':False,'href':'/home/'},
    ...
]

urlpatterns = patterns('',
    (r'^home/$', main_views.home, {'menu':menu()}),
   ...
)

## views.py
from helpers import is_section

@is_section
def home(request, menu):
    context = Context({'menu':menu,...})
    ...

## templates/start.html
{% for section in menu %}
    <li><a href="{{ section.href }}" {% if section.active %} class="active" {% endif %}>
          {{ section.title }}
    </a></li>
{% endfor %}

More like this

  1. Hat-trick for getting categories related to an object group by pablo_PXL 2 years, 4 months ago
  2. Management command decorator by eternicode 2 years, 9 months ago
  3. Using URLs for highlighting sections in menu by diverman 2 years, 10 months ago
  4. twitter_status by zodman 4 years, 9 months ago
  5. Menu/navigation bars in a tag by ep 5 years, 10 months ago

Comments

diverman (on March 6, 2011):

This is similar: http://djangosnippets.org/snippets/2143/

#

(Forgotten your password?)