DRY template rendering decorator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#process a dict and remove by default the 'request' key
cleandict = lambda dlist, ignore = 'request' : dict((key, val) for key, val in dlist.items() if key not in ignore)

from django.shortcuts import render_to_response

#render the template - assume a html format
def render_template(func):
    '''ensure the view using this has the template name matching it'''
    def render(*args, **kwargs):
        variables = func(*args, **kwargs)
        return render_to_response(func.__name__ + '.html', cleandict(variables))
    return render

Example code:

@render_template
def myview(request):
   variables = {'Hello': 'World', 'Monty' : 'Python'}
   return locals()

More like this

  1. DRY template rendering decorator update by jakecr 4 years, 1 month ago
  2. Render Decorator by dahool 4 years, 7 months ago
  3. Qucik Render Template Decorator with Contexts by fatiherikli 2 years, 4 months ago
  4. Template Tag Render Decorator by stephen_mcd 4 years, 1 month ago
  5. Renderer decorator by GaretJax 6 years, 4 months ago

Comments

bram (on February 16, 2010):

your cleandict needs a patch:

>>> cleandict = lambda dlist, ignore = 'request' : dict((key, val) for key, val in dlist.items() if key not in ignore)
>>> cleandict({"req":123})
{}

either:

cleandict = lambda dlist, ignore = ['request'] : dict((key, val) for key, val in dlist.items() if key not in ignore)

or:

cleandict = lambda dlist, ignore = 'request' : dict((key, val) for key, val in dlist.items() if key != ignore)

will fix the problem...

  • bram

#

(Forgotten your password?)