Template Toolkit: how to generate static HTML on any path

Wednesday, April 4th, 2007

My company generates our website using Template Toolkit’s ttree tool. We want our site to be built with absolute paths in the HTML, so we need to be able to accomodate that with file:// URLs when we test it. We use code like this:

The script to invoke ttree in our testing environment:

#!/bin/bash
cd `dirname $0`
rm -r ./out_test/*
ttree -a --relative --pre_process=./lib/config.test \\
         --pre_process=./lib/config.common \\
         --define basedir=`pwd` \\
         -f ./lib/ttree_test.cfg

In lib/config.test:

[% root = 'file://' _ basedir _ '/out_test' %]

In lib/config.deploy (when we build for production):

[% root = 'http://www.ideaworks.com/' %]

This way, rather than hard-coding the testing path in lib/config.test, it Just WorksTM.

Dynamic CSS/JS/HTML in Template Toolkit wrappers

Tuesday, December 19th, 2006

I’ve been asked about this a few times on #tt, so I thought I’d provide it for future Googlers. If you’re looking to optionally include certain files in a Template Toolkit wrapper, it’s very easy. You just provide the file names as a parameter to the WRAPPER call.

First, the wrapper file itself, wrapper.tt:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>[% title %]</title>
<body>
[% IF includes %]
    <div id="sidebar">
    [% FOREACH include_file = includes %]
        [% INCLUDE $include_file %]
    [% END %]
    </div>
    <div id="content">
[% ELSE %]
    <div id="wide_content">
[% END %]

[% content %]</div>

</body>
</html>

And then you call the file like this:

[% WRAPPER wrapper.tt
    title = 'My Title'
    includes = [
        'includedfile1.tt',
        'includedfile2.tt'
    ]
%]

<h1>Content for middle</h1>

[% END %]

It’s pretty straightforward to adapt this to CSS or JS files, or whatever you need to customize in the wrapper.