You might use it like this:
panic% tpage myfile.tt2 > myfile.html
or:
panic% tpage src/myfile.html > dest/myfile.html
It is extremely useful as a command-line tool to process a template
without having to write any Perl code. However, for most uses, be it
an offline script, CGI application, or mod_perl handler,
you'll want to hook the Template
module into your Perl code.
Example D-4. example1/process_template.pl
#!/usr/bin/perl
use strict;
use warnings;
use Template;
# create template processor
my $tt = Template->new( );
# define data
my $data = {
copyright => '© 2002 Andy Wardley',
weblinks => [
{
url => 'http://perl.apache.org/',
title => 'Apache/mod_perl',
},
{
url => 'http://tt2.org/',
title => 'Template Toolkit',
},
# ...and so on...
]
};
# process template - output to STDOUT by default
$tt->process('example.html', $data)
|| die $tt->error( );
After loading the Template module (use
Template;) we create a Template object
via the new( ) constructor method. You can specify
all sorts of options, either as a list of named arguments or by
reference to a hash array. If, for example, you want to put your
templates in a different directory (the default is the current
working directory), then you might do something like this:
my $tt = Template->new( INCLUDE_PATH => 'templates' );
A more complete example might look like this:
my $tt = Template->new({
INCLUDE_PATH => [ '/home/stas/web/tt2/templates',
'/usr/local/tt2/templates',
],
PRE_PROCESS => 'header',
POST_PROCESS => 'footer',
INTERPOLATE => 1,
POST_CHOMP => 1,
});
Once you've created a Template
object, you can call the process( ) method to
process a template. The first argument specifies the template by name
(relative to one of the INCLUDE_PATH directories)
or as a reference to a file handle or scalar containing the template
text. The second optional argument is a reference to a hash array of
data that defines the template variables. A third optional argument
can also be provided to indicate where the output should be directed,
specified as a filename, file handle, reference to a scalar, or
object that implements a print( ) method (e.g., an
Apache request object $r). By
default, the generated output is sent directly to
STDOUT.
This is what it looks like:
<html>
<head>
<title>Some Interesting Links</title>
</head>
<body bgcolor="#ffffff">
<h1>Some Interesting Links</h1>
<p>
Here are some interesting links:
<ul>
<li><a href="http://perl.apache.org/">Apache/mod_perl</a></li>
<li><a href="http://tt2.org/">Template Toolkit</a></li>
</ul>
</p>
<div align="center">
© 2002 Andy Wardley
</div>
</body>
</html>
The external templates (header and
footer) have been pulled into place and the
title reference in the header and
copyright in the footer have
been correctly resolved. The body of the document is built from the
data passed in as weblinks.
 |  |  |
D.4. Template Toolkit Language |  | D.6. Apache/mod_perl Handler |