Skip to content

Instantly share code, notes, and snippets.

@oleoneto
Forked from tejinderss/render_to.py
Created August 7, 2020 04:17
Show Gist options
  • Save oleoneto/388786fac9e6c0486fb68458ebb34034 to your computer and use it in GitHub Desktop.
Save oleoneto/388786fac9e6c0486fb68458ebb34034 to your computer and use it in GitHub Desktop.
render_to decorator for django views
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