Django Template Runner

Posted on

I love working with Django, but you don’t need the entire framework for every web project. If I’m making a small, mostly static site, I like to start with a base index.html and CSS files from html5bp or bootstrap. Without using a templating system, the second page I made would violate one of Django’s design philosophies and a well-accepted good programming practice: DRY – Don’t Repeat Yourself. I know it might be easier to use PHP and that there are even standalone Python templating engines that can do this and more (see Jinja), but I wanted to try my hand at building a class that used Django’s machinery and allowed me to write Django templates and process them using context variables. So I came up with TemplateRunner.

TemplateRunner can be run from the command line anywhere on your machine, but it does make a few assumptions. The template_runner.py module has to be in a location on your Python path, and that location must also contain a contexts.py module a templates folder with the templates (ending in .dj.html):

 my_project/
 └── template_runner
     ├── contexts.py
     ├── template_runner.py
     └── templates
         ├── base_template_example.dj.html
         └── index.dj.html

The contexts module should contain a single constant CONTEXTS which is a dictionary whose keys are the templates and whose values are the context dictionaries for those templates, for example:

 CONTEXTS = {
     'index.dj.html': {
     'page_title': 'Welcome to my Blog!',
     'page_description': 'blog landing page',
     },
     'contact.dj.html': {
     'page_title': 'Contact Me',
     'page_description': 'contact form',
     }
 }

One way to use this class is:

  1. set up your directory structure as described above
  2. make sure the template_runner directory is on your Python path
  3. import the class: from template_runner import TemplateRunner
  4. instantiate a TemplateRunner object: r = TemplateRunner()
  5. process the templates: r.run()

TemplateRunner takes care of configuring basic Django settings for you, processes the templates with the contexts, and saves the output files (.html) alongside the templates:

my_project/
└── template_runner
 ├── contexts.py
 ├── template_runner.py
 └── templates
   ├── base_template_example.dj.html
   ├── index.dj.html
   └── index.html

Once you set things up you can achieve a pretty fast workflow. I use Sublime Text 2 with the SublimeREPL package, so I don’t even have to leave the editor to run my templates. I just made this for my own personal use, but if you find it useful you can find the source code on GitHub.

What’s your preferred way to go about templating when building a small, mostly static site?

Leave a Reply

Your email address will not be published. All fields are required.