Created
October 29, 2012 10:40
-
-
Save tejinderss/3972895 to your computer and use it in GitHub Desktop.
render_to decorator for django views
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from django.http import HttpResponse | |
from django.shortcuts import render | |
from django.utils.functional import wraps | |
from django.utils import simplejson | |
def render_to(view=None, template_name=None): | |
""" | |
Decorator to reduce boilerplate of rendering view to template. | |
Requires that the view returns a dictionary of context as opposed | |
to the rendered template. Decorator can be called with or without | |
keyword arguments. If called without arguments there is no need to | |
add a method call using @render_to(), it will work as @render_to. | |
Examples: | |
@render_to(template_name='home.html') | |
def home(request) | |
... | |
@render_to | |
def home(request) | |
... | |
""" | |
def decorated(view): | |
def wrapper(request, *args, **kwargs): | |
template = template_name or '%s.html' % (os.path.join(view.__module__.split('.')[0], view.__name__)) | |
context = view(request, *args, **kwargs) | |
if request.is_ajax(): | |
return HttpResponse(simplejson.dumps(context), mimetype='application/json') | |
return render(request, template, context) | |
return wraps(view)(wrapper) | |
if view is None: | |
def decorator(view): | |
return decorated(view) | |
return decorator | |
return decorated(view) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment