DRY template rendering decorator update

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#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
from django.http import HttpResponse

#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):
        view_response = func(*args, **kwargs)
        if isinstance(view_response, HttpResponse):
            return view_response
        return render_to_response(func.__name__ + '.html', cleandict(view_response))
    return render

Example code:

@render_template
def myview(request):
   variables = {'Hello': 'World', 'Monty' : 'Python'}
   if request.POST:
      return HttpResponseRedirect('/somewhere/')
   return locals()

More like this

  1. DRY template rendering decorator by pfylim 3 years, 3 months ago
  2. Convert LaTeX templates to various output formats by blizz 6 years, 2 months ago
  3. Auto rendering decorator with options by Batiste 5 years, 3 months ago
  4. Resource by zvoase 4 years, 7 months ago
  5. Create PDF files using rml and django templates by mporrato 5 years, 10 months ago

Comments

jakecr (on September 18, 2010):

Why the negative score? Please tell me if something is wrong with this!

#

(Forgotten your password?)