Python Based Template Engine

Last updated: Feb, 2010

download: source(shell script)

Description:

My web site is relative small and I am the only person that edits and updates the pages. It is important that my pages are portable, easy to deploy and relatively low in memory consumption while running on an Apache web server. At the same time I would like to change the look and feel of the pages if necessary without too many problems. CMS systems such as Drupal and Joomla offer a lot of functionality but are relative 'heavy' in terms of memory consumption, and relative complex as you have to deal with database backends, PHP, and many other configuration options. These systems are great if you are running a slightly more complex, multi user and interactive 2.0 web site, but this is not the case for my site (I like to keep it simple).

A simpler approach is to deploy a template engine on the server side. Several good Java and Python (e.g Cheetah) based engines are available but this means either installing a web server like Tomcat (relative high memory consumption), or setting up Apache with something like mod_python (doable, but the less modules the better).

Not satisfied with the solutions outlined above since they did not match my requirements, I wrote a simple 350 line Python program that serves as an offline template engine. Content is written in a simple XML format in which variables are defined. These variables are also available in the templates. A simple search and replace function in Python adds to each content file the template information. Templates themselves can include other template files, which makes it easy to include for example a generic menu in different templates. The Python program also generates a site map of the site making it easy to navigate your site in a few clicks.

As long as you do not change your templates (which is usually not that often), you only need to (re-)generate new or updated pages. The image below shows a simple schematic on how the offline template engine works. As the number of pages on my site is relative small (between 50 to 100 pages), re-generating the site when the templates change is not that much work. The result is a collection of static html pages which are easy to deploy on a standard configured Apache web server without any PHP or MySQL deployed (less components means it is easier to secure and manage).

offline template engine The zip file referenced above contains the Python code with a sample configuration and some template files to try it out.