Introduction to Template::Toolkit
Template::Toolkit is an awesome Perl module to combine data with text or HTML templates to generate pages. It has excellent documentation, but it is always nice to see simple but working examples that you can copy-and-paste and start tweaking.
Install Template Toolkit
Before you start using it you will have to install Template::Toolkit.
The code
examples/tt/create.pl
use strict; use warnings; use Template; my $tt = Template->new({ INCLUDE_PATH => './templates', INTERPOLATE => 1, }) or die "$Template::ERROR\n"; my %data = ( title => 'This is your title', languages => ['English', 'Spanish', 'Hungarian', 'Hebrew'], people => [ { name => 'Foo', email => 'foo@perlmaven.com' }, { name => 'Zorg' }, { name => 'Bar', email => 'Bar@perlmaven.com' }, ], ); my $report; $tt->process('report.tt', \%data, \$report) or die $tt->error(), "\n"; print $report;
The template
examples/tt/templates/report.tt
[% title %] =================== Languages ---------------- [% FOREACH name IN languages %] * [% name %] [% END %] People ---------------- [% FOREACH person IN people %] * [% person.name %] [% IF person.email %]mail: [% person.email %][% END -%] [% END %]
Directory layout
. ├── create.pl └── templates └── report.tt
Execution
$ cd to-the-root-dir-where-create.pl-is-located $ perl create.pl
The Result
This is your title =================== Languages ---------------- * English * Spanish * Hungarian * Hebrew People ---------------- * Foo mail: foo@perlmaven.com * Zorg * Bar mail: Bar@perlmaven.com
Let me point out the empty rows between the languages. They are there because TT by defaults add a newline at the end of the tag we are inlcuing. You can change this by adding a dash at the closing part of the expression. This is what happened in the rows of the People where on line 15 you can see a dash before the last percentage sign: -%].
Published on 2020-08-19