Login

render_to

Author:
asolovyov
Posted:
June 24, 2008
Language:
Python
Version:
.96
Score:
15 (after 15 ratings)

Decorator, written for views simplification. Will render dict, returned by view, as context for template, using RequestContext. Additionally you can override template, returning two-tuple (context's dict and template name) instead of just dict.

Usage:

@render_to('my/template.html')
def my_view(request, param):
    if param == 'something':
        return {'data': 'some_data'}
    else:
        return {'data': 'some_other_data'}, 'another/template.html'
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def render_to(template):
    """
    Decorator for Django views that sends returned dict to render_to_response function
    with given template and RequestContext as context instance.

    If view doesn't return dict then decorator simply returns output.
    Additionally view can return two-tuple, which must contain dict as first
    element and string with template name as second. This string will
    override template name, given as parameter

    Parameters:

     - template: template name to use
    """
    def renderer(func):
        def wrapper(request, *args, **kw):
            output = func(request, *args, **kw)
            if isinstance(output, (list, tuple)):
                return render_to_response(output[1], output[0], RequestContext(request))
            elif isinstance(output, dict):
                return render_to_response(template, output, RequestContext(request))
            return output
        return wrapper
    return renderer

More like this

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

Comments

alfor (on April 6, 2010):

wonderful snippet, this should be in django.shortcuts

#

cometsong (on September 1, 2017):

Make sure you include:

from django.shortcuts import render_to_response
from django.template import RequestContext

in your views.py.

Excellent simplification with this decorator!

#

Please login first before commenting.