Why we use as_html
decorator (known as render_to
)? Because we need to provide context_instance
argument to render_to_response
function:
from django.template import RequestContext
from django.shortcuts import render_to_response
def show_entry(request, slug):
entry = get_object_or_404(Entry, status=Entry.statuses.published, slug=slug)
return render_to_response(
'blog/entry.html',
{'entry': entry},
context_instance=RequestContext(request)
)
We write less code with decorator:
from common.decorators import as_html
@as_html('blog/entry.html')
def show_entry(request, slug):
entry = get_object_or_404(Entry, status=Entry.statuses.published, slug=slug)
return {'entry': entry}
This is just example, normally we should use generic view. Now let’s see how our view will change, if we’ll use new render
shortcut:
from django.shortcuts import render
def show_entry(request, slug):
entry = get_object_or_404(Entry, status=Entry.statuses.published, slug=slug)
return render(request, 'blog/entry.html', {'entry': entry})
Just few changes, but the latter is better. Ivan Sagalaev wrote nice comment about render_to
decorator, but another reason not to use it is that template name is at the start of function while dictionary of values is at the end. It’s good to keep all template-related code in one place, at the end of your function.
This blog is about things I encounter while doing web and non-web software development.