Django: Easy template fallback selection

Django has some pretty neat features that allow for simple template selection.

You can generate a list of templates you wish to use, and it'll go through and see if they exist. The first one that exists will be returned.

from django.template.loader import select_template

An example below:

def section_page(request, section_slug, subsection_slug):
c = { 'title': 'blah blah blah', 'section': section_slug, }

template_list = (
'section/home_%s_%s.html' % (section_slug, subsection_slug),
'section/home_%s.html' % section_slug,

return render_to_response(select_template(template_list), c, context_instance = RequestContext(request)

Now following the given example, if we tried to load a section such as "funny" and the subsection of "comics", it'll see if you have a customised layout for "home_funny_comics.html" and use it.

If that file doesn't exist, it'll try to get "home_funny.html" and use it.

Now if that doesn't exist, as last resort it'll use "base.html" as the template.

If none of those exist, it'll raise an exception.

Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog