Login

DRY template rendering decorator

Author:
pfylim
Posted:
February 16, 2010
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

in this case the 'render_template' decorator assumes there is a myview.html template. this keeps things simple and you DRY. Hope it helps.

Regards, Paul

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

#

Please login first before commenting.