Thursday, April 17, 2008

Flexible CGI output with HTML templates

Consider our free search engine script. It is an excellent application, but it wouldn't be very helpful for others if it could display its results only in the output page format that we use for our site. Somebody else's site will probably need the output page to contain site-specific navigation links, different colors, or even a completely different layout concept. It is not uncommon to see CGI programs that contain the HTML code that is returned to the browser, inside one or more print statements in the code of the script. Clearly this is not a good idea, since it makes it at least difficult, if not nearly impossible, for a non-programmer to alter the output format. At best, a webmaster with little understanding of perl could identify the HTML code inside the program and alter some obvious items, like colours. Still, as applications grow more complex, this approach becomes even more difficult to manage. If control structures (if, while etc) are being used to generate the output, or if there are multiple pages of output composed by chunks of html that are being generated in different places in the code, even someone who is comfortable with perl could find it hard to figure out how to alter the look of the output. And this is not the only problem. The code itself becomes difficult to manage and maintain. Program code is difficult to read an maintain on its own right. Cluttering it with HTML here and there does not help the situation at all. I will describe a different approach to the problem here, the one that we use for our programs and which proves to be a very good solution for almost any type of application. The idea in this approach is to isolate the HTML code in a separate file, which we call a template. A template is just like any regular HTML file, but it contains some special markup dictating where to insert the various dynamic data that will be produced by the CGI program. The program need only be concerned with generating the actual dynamic content, then it can simply insert it in appropriate place in the template and thus come up with the final output.

What a template looks like

The only thing that sets a template apart from a regular HTML file is that it contains comments of the form . Such comments will be identified by the CGI program and replaced with the appropriate value for variable. The template may contain references to as many such variables as the CGI program is made to define. For example, take our search engine program. On the top of the search results page there appears some text saying what search was made and how many results it came up with. Assuming the program defines variables search_string and total_results, our template could look like: ... Your search for resulted in matching pages. ...

Filling in the template

A simple way of doing this is the following: open(TEMPLATE, $template_file); while(