Great. I adore TT and this example goes to the root of why and why I break from the View purists who say TT is a disaster and you should use something like HTML::Template. These simple loop controls can solve many common display logic problems.
TT can do just about anything. Beware of moving too much into it (it can write files, run macros, run plain Perl, do recursion, etc, etc, etc). If you want a ton of code in templates, Mason is probably the right choice. TT lets you separate and plugin really well though so you can do your own methods and filters, for example, without writing anything but glue code; The Right Way to Do It™. Just another example-
use warnings;
use strict;
use Template;
use Lingua::EN::Numbers::Ordinate "ordinate";
my %config =
( FILTERS => {
ordinal => sub { ordinate($_[0]) },
ordinal_html => sub {
my $ord = ordinate($_[0]);
$ord =~ s,(\D\D)\z,<sup>$1</sup>,;
return $ord;
}
}
);
my $tt2 = Template->new(\%config);
$tt2->process(\*DATA, { numbers => [ 0 .. 121 ] })
or die $tt2->error;
__DATA__
[% FOR i IN numbers %]
Plain: [% i | ordinal %] -- HTML: [% i | ordinal_html %]
[%-END %]
I'd also point you toward Template::Alloy. It's a well behaved implementation of the TT2(3) syntax with a few improvements and supports several other template types. I've used it on my last couple of projects and haven't hit any reasons to go back.
|