The Template Toolkit, Part Three
In the previous two columns, I introduced my templating system of choice, the Template Toolkit. Continuing from where I left off, let’s look at some of the other features of the Template Toolkit (TT), including how to configure TT and use it from Perl, from the command line, and embedded in Apache.
Sunday, August 15th, 2004
In the previous two columns, I introduced my templating system of choice, the Template Toolkit. Continuing from where I left off, let’s look at some of the other features of the Template Toolkit (TT), including how to configure TT and use it from Perl, from the command line, and embedded in Apache.
Using the Template Toolkit from Perl
The simplest TT code looks like this:
use Template; my $template = Template-new(%CONFIG); $template-process($filename,%VARS);
This sets up a $template object using the configuration parameters in %CONFIG (described later), and then executes $filename as a template, passing the pre-defined variables of %VARS, sending the result to standard output. $filename might be found along a search path (see INCLUDE_PATH later), or might be a filehandle. For example, my favorite trick is using DATA, as in:
use Template; Template-new-process( *DATA, # process DATA { a = 1, b = 2, # passing these constants argv = @ARGV, # and the arg list env = %ENV, # and the environment }, ); __END__ a is [% a %] and my home is [% env.HOME %]. [% FOREACH arg = argv; “The command line args are: ” IF loop.first; arg; “, ” UNLESS loop.last; “.n” IF loop.last; %] Rather than sending the output to stdout, I can capture the output into another variable:
my $output; $template-process($filename, %VARS, $output);
I can also provide the template directly as a scalar reference: