An ASP Template Class, Part 2By James Q. Stansfield
In Part 1 we looked at separating content and layout using cascading style sheets, include files, and custom functions. In this part, we'll examine using templates to keep content and layout separate!
Recently I've started working with template files, which in my opinion are much better than the previous two methods. With template files, the designer can work with a single HTML file. The designer can add the appropriate 'tags' where needed or leave that up to the developer. Below you can see an example of a template file:
As you can see by the example this is a standard HTML file the only difference being that there are a few tags that are bounded by
%]. These are the tags that will be replaced by dynamic content. Please note that you are not limited to the number of tags you can have on a given page, or the number that can reside on a single line.
I've written a class that will take this, or any template file, and parse it with user-defined values stored in a Dictionary object. Below is the ASP file that creates an instance of the class, defines the tags and their values and generates the HTML.
This example only loads one page and doesn't address the needs of most websites. However, for large multiple page sites you could put a default set of tags into an include file that is loaded on every page, then you need only specify what template file to load and add any page specific tags before using the GenerateHTML method.
The parseTMPL class resides in the
parse_cls.asp file. I won't get into it in this article as the file itself is documented.
Download the accompanying files and test out the class for yourself (or
try out the on-line live demo).
Using templates to aid in the delivery of your website is most valuable when the time comes to change the look & feel of your existing site. Simply change a template file that controls the layout and style specific HTML code is much easier than traversing multiple files of spaghetti code line by line.
The class has room for improvement:
1. Error handling needs to be added.
2. The class is limited to returning a string or variable for any tag.
In a future article I will expand upon the class and it's capabilities and show how this can be used in the creation of a portal site. I will also show how mini-templates can be used within a larger template for even greater functionality!