I thought I might as well share a small snippet of django code that I use all the time in my projects. The renderRequest function simplifies rendering of templates using RequestContext but also includes a SITE_URL variable for some easier.
# renderRequest by Colton Provias
from django.http import HttpResponse
from django.template import RequestContext, loader
# Replace with your site's base URL
SITE_URL = "http://example.com/"
def renderRequest(request, template, vars):
vars["SITE_URL"] = SITE_URL
vars["PATH"] = request.path
return HttpResponse(loader.get_template(template).render(RequestContext(request, vars)))
The usage of this function is easy. Instead of renter render_to_response or whatever other method you are using, use the following:
return renderRequest(request, template, vars)
For example, let’s say that I have a template named “demo/base.html” and wanted to send it a couple of variables:
return renderRequest(request, "demo/base.html", {"vara": "Hello", "varb": "World"})
In the template, you can then use {{ vara }}, {{ varb }}, {{ SITE_URL }}, and {{ PATH }}. Also, since we are using RequestContext, you also get the added benefit of {{ user }}, {{ messages }}, and etc.