Server Side Include (SSI) Templating

October 19, 2005 - 2 minute read -

Templating for web pages is a method to separate form from content. Just like HTML and CSS separate form from content, a templating system allows you to further separate the common structure of a page from the "Stuff" that people want to read. Is there a best way to do templating? I don't know, but here's a way that I think is good:

Often times when people do templating they include a common header, a common footer and possibly navigation in each of their source HTML files. Over time the size of the site grows and the number of pages becomes large. If you ever want to change the layout of the site, you often find that there are changes that you have to make in each file because the layout has creeped into each one.

By thinking about Templating in a slightly different way, you can turn the problem on it's head and never worry about it again. Rather than having 4 files:

  1. page.html
  2. header.html
  3. footer.html
  4. nav.html

(page.html includes header.html, footer.html and nav.html)

You can have 3 files:

  1. page.html
  2. page.body.html
  3. template.html

In this scheme page.html is a level of indirection that looks like:

<!--#set var="body" value="index.body.html" -->
<!--#set var="page.title" value="Hi, I'm a Title" -->
<!--#include file="template.shtml" -->

What you see with the above code is that the main included file is the template.shtml page. The other 2 directives are setting parameters that will be used in the template to load the proper body content and set the title. You can create more variables like this if you need to.

page.body.html will have just the main content of the page.

Blah, blah, I'm the content of the page.

template.html will then have the entire markup of the site except for the body. It can have includes if need be, but its main purpose is to contain the structure of the site including common elements like headers, footers, navigation, etc. The template.html page will include the value from the body variable set in the page.html (as described above) and include it in the proper place:

<head>
<title>Common Title | <--#echo var="page.title" --></title>
</head>
    ...</p>
<div id="primaryContent">
<!--#include virtual="${body}" -->
</div>

This lets you focus on the content when you want to worry about content and focus on layout when you want to worry about that.