Creating templates with Text::Template

By this stage in the day you have probably spent a great deal of time outputting HTML either via a long list of print statements or by using a "here document" or other shortcut. What if you wanted to have a template HTML output file which was filled in with the appropriate variables?

Luckily, there is a Perl module to do this, called Text::Template. Unluckily, it uses a concept we haven't covered yet, but which we will now explain.

Text::Template is different to the other modules we have used so far today, in that it is an object oriented module. Object oriented Perl modules can be very powerful, but require some background knowledge to understand how they work.

Introduction to object oriented modules

Before embarking on this task, we need to have an understanding of how Perl's object-oriented modules work. Not all modules are object oriented (URI::Escape, for example, is not), and some can be used either way (CGI is one of these), but some require us to work with them in this way.

Read perldoc CGI if you want to know all about the OO interface to the CGI module, which provides many additional features.

A software object, like a real-life object, has attributes (things that describe the object) and methods (things you can do with, or to, the object). Consider the real-life example of a cup:

Table 6-1. Attributes and Methods of a cup

ObjectAttributesMethods
Cup

  • colour

  • handle (does it have one?)

  • contents (water, coffee, etc)

  • fullness

  • drink from it

  • fill it up

  • smash it

Note that when you smash a cup, you aren't smashing the generic class of cups, but rather a specific instance - this cup, not "cups in general". This is what we call an instance of a class -- remember that, as we'll use it later.

Using the Text::Template module

Like the cup, our text template has attributes and methods.

Table 6-2. Attributes and Methods of Text::Template

Text::Template

  • TYPE - the type of template it is, eg a file, a string you created earlier, etc

  • SOURCE - the filehandle or variable name in which the template can be found

  • fill_in() - fill in the template

Before we can actually use these attributes and methods in any useful way, we have to create a new instance of the class. This is the same as how we needed a specific cup, rather than the general class of cups.

# using the class in general
use Text::Template;  

# instantiating the class and setting some attributes for the new instance
my $letter = new Text::Template{'TYPE' => 'FILE', 'SOURCE' => 'letter.tmpl'};

We can then perform a method on it, thus:

my $finished_letter = $letter->fill_in();

This will fill in any variables found in the template file.

Exercise

  1. Type perldoc Text::Template and look at the documentation for this module

  2. cgi-bin/letter.cgi implements the example above. Examine the source code.

  3. Make some changes to the letter template and see if they work.