django decorator

 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
44
from django.shortcuts import render_to_response
from django.template import RequestContext
def render_to(default_template=None, template_key=None):
"""
Decorator for Django views that sends returned dict to render_to_response function
with given template from a string or variable and RequestContext as context instance.
If view doesn't return dict then decorator simply returns output.
Parameters:
- default_template: template name to use
[optional]
- template_key: if given, render_to will use this template name (and will override default)
Examples:
@render_to('template.html')
def foo(request):
... # some data processing
return {'bar': bar}
@render_to('template.html','template')
def foo(request, category):
... # some data processing
template_name = '%s.html' % category
return {'bar': bar, 'template': template_name}
@render_to(template_key='template')
def foo(request, category):
... # some data processing
template_name = '%s.html' % category
return {'bar': bar, 'template': template_name}
"""
def renderer(func):
def wrapper(request, *args, **kw):
output = func(request, *args, **kw)
if not isinstance(output, dict):
return output
tmpl = output.pop(template_key, default_template)
return render_to_response(tmpl, output, context_instance=RequestContext(request))
return wrapper
return renderer