Using templates with Perl/CGI
Most Web applications by nature use a lot of HTML. Think about a Web-based email program such as Hotmail. HTML is used to display numerous pages including the login screen, mailbox, read message, send message, folders, menubar, setup options, and many other pages.
Finding a new home for all that HTML
The best way to organize your HTML Templates is to put them near your program (either in the same directory or a sub directory named "/templates/") and to give them a good descriptive name. I usually make the first character of the filename an underscore followed by the program name and the program section. I use the underscore at the beginning to differentiate between regular HTML files and HTML templates.For example, pretend we were to create a Web-based email program called "Web Mail", our templates may be named as follows:
_webmail_login.html # login
_webmail_message_list.html # list messages
_webmail_message_read.html # read message
_webmail_message_send.html # create/send message
_webmail_message_erase.html # erase message
_webmail_message_erase_confirm.html # confirm erase
_webmail_logoff.html # logoff
This makes it easy to see at a glance what the file is for and even easier to come back later and make any changes or see what a specific page looks like. Also, if you work with other web developers and designers, they can make changes without fear or messing up your program by accident or remembering to backslash all the @ symbols.
Displaying templates in Perl/CGI
Before we can start moving all that HTML out of our Perl/CGI programs and into HTML template files we need some way to display them. So, we're going to create a Perl subroutine called&Template |
sub Template {
local(*FILE); # filehandle
local($file); # file path
local($HTML); # HTML data
$file = $_[0] || die "Template : No template file specified\n";
open(FILE, "<$file") || die "Template : Couldn't open $file : $!\n";
while (
Most of this is pretty basic, we're just opening a template file, reading the contents and passing it back to the program. The trick is the following regular expression that searches for Perl variables in your HTML template (i.e., "$date") and substitutes them with the value of the that variable as defined in your program:
$HTML =~ s/\$(\w+)/${$1}/g;
