Template Toolkit Example

This is just a short example on how to use the basic features of Andy Wardley's Template Toolkit. You'll need a copy of Perl installed, and you can get the Template Toolkit from CPAN.

We'll start by just showing how to get a bit of data onto a page. Lets assume we have a variable called $robs_data in our Perl script that we want to insert into our template.

The code in the template will look something like this...

The value of $robs_data is [% robs_data %].

Lets have a quick look at the Perl needed to fill this in.

#!/usr/bin/perl -w use strict; use Template; my $robs_data = 'Not very much'; my $template_filename = '/where/my/template/is.whatever'; my $data = { 'robs_data' => $robs_data }; my $template = Template->new(); $template->process($template_filename,$data) || die $template->error();

Running that script will give the following result to STDOUT.

The value of $robs_data is Not very much.

So what has gone on here? Well the magic occurs near the end of the script. The last line of the script we ask the Template Toolkit to load the file found in $template_filename, and populate it with the data found in our hash reference $data. In $data we had earlier created an entry called 'robs_data' that pointed to the variable $robs_data. The Template Toolkit took this value, and when it saw [% robs_data %] it replaced it.

Now lets suppose we wanted to extend this a little. Suppose we have an array of data we want to display nicely, how would we go about this? Well it's nice and easy in the Template Toolkit. Lets add our array to the earlier Perl code, and change our definition of $data.

my @languages = qw(Perl Java C);

my $data = { 'robs_data' => $robs_data, 'programming_languages' => \@languages };

We've called the hash element 'programming_languages' and we've pointed it to a reference to our array @languages.

Now lets look at how we can change the template to display the data from our array.

The value of $robs_data is [% robs_data %]. Which of the following languages is this example for? [% FOREACH language = programming_languages %] * [% language %]? [% END %]

This will produce the following results to STDOUT when we run our Perl script.

The value of $robs_data is Not very much. Which of the following languages is this example for? * Perl? * Java? * C?

As you can see, it's gone though each element of the array programming_languages and put the current value into the variable language. It then allows us to display it the same way we did earlier with robs_data each time we iterate through the loop.