This article was last updated Monday, 13 December 2004. View a newer version at my site, hardanswers.net/template-based-site

Templates

Creating static pages for a site works well when the site is small, but gets very cumbersome as the site becomes bigger – a site-wide change has to be performed in every single file on the site, taking a lot of time and effort. The usual way to overcome this is by the use of templates. A template is a single page or style that is applied to a whole site, meaning that most site-wide changes can be done by simply editing the template, rather than every file in the site – saving a lot of time and effort.

The system I’ve used allows me to store the content in plain XHTML files, easily created and maintained by anyone using any standard XHTML editor, such as Dreamweaver. This makes it particularly easy to deploy new content and modify existing content.

The basic logic is that I have a single file that applies all the site-wide features, such as common headers, footers and styles, and the individual page’s content is included into this file and displayed to the user.

The basic concept

However, because the individual pages are stored as complete XHTML files, and the resulting output page must also be a complete XHTML file, it is not possible to simply include the entire individual page into the template. The result would look something like this, which is not a valid XHTML page.

Invalid XHTML page

To overcome this problem, I have a function that accepts a file name and a tag name, and returns the contents of that tag from the given file.

Parse tag function

I can now include just the body tag from each individual page, as the content of my template. A simple template such as this will now produce a valid XHTML page.

Simple template

Valid XHTML page

With a bit more code, you have yourself a simple, functional template.

Simple, semi-functional template

Care must always be taken to ensure that anything able to be externally passed into a file isn’t malicious. A simple function such as this attempts to find PHP and HTML files, and returns a default PHP file if none are found. This can prevent anyone attempting to access anything unusual.

Individual files are now stored as XHTML or XML. XHTML files are parsed for their body, style and title tags and these tags are then included into the resulting output. This allows a simple template system where the content can be created with any XHTML capable editor, and I have found this to be the simplest way of creating a consistent and easily updateable style across a site.

There are several advantages and a few disadvantages to this approach.

Disadvantages include:

Advantages include:

For further information on:

 

Last updated Tuesday, 20 November 2012