[Igor Sobreira] Replacing render_to_response with direct_to_template in Django

Published on: 11/09/2010 20:29h

You certainly have already used render_to_response to render your templates, it’s a very convenient shortcut:

from django.shortcuts import render_to_response

def myview(request):

    ...

    return render_to_response('template.html', {'foo': ['one', 'two']})

At least until you need to use context processors, then you start writing code like this

from django.shortcuts import render_to_response

from django.template import RequestContext

def myview(request):

    ...

    return render_to_response('template.html', 

            {'foo': ['one', 'two']},

            context_instance=RequestContext(request))

this context_instance argument is the boilerplate code you will always need to make context processors work. I think it’s too much typing, and I’m lazy, so I prefer to use the direct_to_template generic view:

from django.views.generic.simple import direct_to_template

def myview(request):

    ...

    return direct_to_template(request, 'template.html', 

            {'foo': ['one', 'two']})

You don’t need the context_instance argument anymore, and you save one import.

But! There is one simple detail when passing extra context to this view, if a value in your dict is a callable, it will call and pass the result to template. It can be useful, but is something to keep in mind, if you’re trying to pass a callable to template.

Read the source code to understand how it works.

By Igor Sobreira