March 18, 2008
A minimalistic web site compiler
The setup of small non-dynamic web sites is an often recurring task. Unfortunately, there’s a lot of repeated content, most of it in the header of the sites that doesn’t change except for the title.
SSI doesn’t really help because its syntax is clumsy and the files are compiled again on each request. It also needs to be enabled on the target host.
A solution that compiles standard HTML from templates is best for performance and portability. It’s possible to use on of the many HTML template toolkits out there, but why bother? All I want is a standardized header and footer and a page title varying with each HTML file.
So let’s do just that:
#!/bin/bash set -e OUTDIR=./build mkdir -p "$OUTDIR" # wrap header and footer, set <title> from first line of body for f in {page1,page2,page3}.html; do TITLE=$(echo $(head -n1 $f) | perl -p -e 's/^TITLE: *(.*?)$/$1/') (sed "s|TITLE|$TITLE|" header.html ; sed '1d' $f; cat footer.html) > "$OUTDIR/$f" done # auxiliary files for f in logo.png default.css; do cp $f "$OUTDIR/$f" done </title>
The files that get wrapped into header and footer need to set their title on the first line:
TITLE: my page title <p>So this is it...</p>
If you don’t like Perl, you can also whip up a sed or awk script in its place.