Chapter 3.  Templating Tools

Table of Contents

Chapter 3. Templating Tools

A recent thread on comp.lang.perl.moderated enumerated the Perl rites of passagethe perfectly good wheels that every journeyman Perl programmer reinvents. These were found to be a templating system, a database abstraction layer, an HTML parser, a processor for command-line arguments, and a time/date handling module.

See if you recognize yourself in the following story: you need to produce a form letter of some description. You've got a certain amount of fixed content, and a certain amount that changes. So you set up a template a little like this:

    my $template = q{
        Dear $name,

        We have received your request for a quote for $product, and have
        calculated that it can be delivered to you by $date at a cost of
        approximately $cost.

        Thank you for your interest,

        Acme Integrated Foocorp.

Then you struggle with some disgusting regular expression along the lines of s/(\$\w+)/$1/eeg, and eventually you get something that more or less does the job.

As with all projects, the specifications change two days after it goes live, so you suddenly need to extend your simple template to handle looping over arrays, conditionals, and eventually executing Perl code in the middle of the template itself. Before you realize what's happened, you've created your own templating language.

Don't worry if that's you. Nearly everyone's done it at least once. That's why there's a wide selection of modules on CPAN for templating text and HTML output, ranging from being only slightly more complex than s/(\$\w+)/$1/eeg to complete independent templating languages.

Before we start looking at these modules, though, let's consider the built-in solutionthe humble Perl format.

    Table of Contents
    © 2000- NIV