Skip to content

Instantly share code, notes, and snippets.

@brehaut brehaut/render.py
Last active Dec 21, 2015

Embed
What would you like to do?
simple views and contexts for django
from render import render
def some_context(request):
return {…}
def some_different_context(request):
return {…}
@render("template.html")
def viewname(request):
return [
some_context(request),
some_different_context(request)
]
from collections import Mapping
from functools import reduce
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template import RequestContext
def merge(dicts):
"""Merge an iterable of dictionaries into one dictionary
If python was actually cool:
def merge(dicts):
return reduce((lambda acc, d: acc.update(d) or acc), dicts, {})
"""
d = {}
for d_ in dicts:
d.update(d_)
return d
def render(template):
"""render is a variant on django-annoying's view decorating function.
render knows about template context dictionaries, and iterables of dictionaries
(that are merged with merge above).
the template name is passed to render. If a view returns an django HTTP
response object then that is returned in its place.
"""
def decorator(view):
def wrapper(request, *args, **kwargs):
res = view(request, *args, **kwargs)
if isinstance(res, HttpResponse):
return res
elif not isinstance(res, Mapping):
context = merge(res)
else:
context = res
return render_to_response(template, context, RequestContext(request))
return wrapper
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.