Template layers / skins for Django

With Django I often have cases where I want to serve different templates based on certain request-specific criteria (usually the hostname used for the request). For example

  • Different "skins" for different domains
  • A different "visitor skin" all together (while the backoffice has a generic admin skin)
  • A/B testing

You can either fix this hardcoded in your views, which requires a lot of repetition and is very inflexible, use separate packages for the template skins and put them in different deployments, each with their own INSTALLED_APP path, which will cause Django to search different paths, or you can use the django_layers package I just created.

It allows you to define different sets of templates ("layers")  and switch between them using a simple get_layer function.

For example, with WheelCMS you could have the following get_layer() function:

def get_layer(request):
if request.get_host() in ("example.com", "www.example.com") or \
request.REQUEST.get('preview', False):
return 'visitor'

This will instruct the django_layers Template Loader to load the 'visitor' skin if the site is accessed as (www.)example.com (but not, for example, admin.example.com) or if a 'preview' argument is present, e.g. http://admin.example.com/blog/?preview=1

Which, in effect, means that <anypackage>/layers/visitor/ is additionally searched for templates.

Code and documentation is of course on github.

Travis CI status for django_layers

 

 

Last updated July 30, 2013, 4:50 p.m. | filed under django | django python templates
comments powered by Disqus