Perlish – Text::Template

Posted by Joe Topjian on March 30, 2011 under Development | Be the First to Comment

Introduction

Most scripts or applications involve some type of output and reporting. If the script or application starts growing, the output can become more complex. Mixing the code that formats and displays your output in the same area as the code that performs the logic can become messy. Templating is a popular solution to this problem. In this article I will quickly cover Text::Template.

Table of Contents

Text::Template

Text::Template is a simple to use templating system for Perl. It’s not restricted by output format, so you can use it for text, HTML, XML, or really any type of readable output.

Here’s a quick example that shows how to use Text::Template with a simple report.

The Report Code

This short script emulates a report of suspended users. For the sake of simplicity, I am just referencing the suspended users by a manually created hash. The script then calls the Text::Template function fill_in_file, which plugs in all data to the template (seen later) and then prints the results.

#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;
use Text::Template qw/ fill_in_file /;

my $users = { 
    moe => 'Wed Mar 30 12:23:26 2011',
    larry => 'Tue Mar 29 09:15:55 2011',
    curly => 'Mon Mar 28 20:45:18 2011',
};

my $data = { 
    title => 'Suspended Users Report',
    users => \$users,
};

say fill_in_file('report.tpl', HASH => $data);

The Template

Now here’s the template that will be used, located in a dedicated file called report.tpl. Perl will interpret anything enclosed in { }‘s — this includes variables, functions, and full blocks of code:

{$title}
=======================================
Generated on {localtime}
---------------------------------------

{
    for my $user (keys %{ $users }) {
        $OUT .= sprintf("%-10s %28s\n", $user, $users->{$user});
    }   
}

The use of the $OUT variable is a special feature of Text::Template. In short, it will collect the output of a loop and print the final results to the rendered template.

The Full Output

When the script is run, here is the output:

Suspended Users Report
=======================================
Generated on Wed Mar 30 15:35:09 2011
---------------------------------------

larry          Tue Mar 29 09:15:55 2011
curly          Mon Mar 28 20:45:18 2011
moe            Wed Mar 30 12:23:26 2011

Conclusion

For a simple example such as the one above, including the output and formatting code would not have been that bad. However, as scripts become larger and more complicated, placing the formatting code into a dedicated template file can bring ease of comprehension by more structure. Although Perl has several templating modules available, I’ve found Text::Template to be very flexible and simple to understand.

Add A Comment