so it's a real limitation?
It could be regarded as a feature! :-)
I would argue that it is the job of your code to determine what is to be presented and HTML::Template's job to determine how it is presented. How would your template look if there were a series of nested loops with conditionals at every step of the way?
The docs mention that if your template has too many ifs, elses and unlesses you should really have a look at your code and reconsider.
Even with what is often considered a more 'powerful' templating system like Template::Toolkit the docs also discuss this question. Apologies for the length of the quote but I think it addresses the point very well.
The directives that the Template Toolkit provide implement their own mini programming language, but they're not really designed for serious, general purpose programming. Perl is a far more appropriate language for that. If you embed application logic (e.g. Perl or other scripting language fragments) in HTML templates then you risk losing the clear separation of concerns between functionality and presentation. It becomes harder to maintain the two elements in isolation and more difficult, if not impossible, to reuse code or presentation elements by themselves. It is far better to write your application code in separate Perl modules, libraries or scripts and then use templates to control how the resulting data is presented as output. Thus you should think of the Template Toolkit language as a set of layout directives for displaying data, not calculating it.
I think the reference to reusing code is very significant here.
A trivial example that would do what your template snippet is trying to do might look something like
#!/bin/perl5
use strict;
use warnings;
use HTML::Template;
my @m_options = (
{name => q{one}, type => q{a}},
{name => q{two}, type => q{b}},
{name => q{three}, type => q{c}},
{name => q{four}, type => q{a}},
{name => q{five}, type => q{b}},
{name => q{six}, type => q{c}},
{name => q{seven}, type => q{a}},
{name => q{eight}, type => q{b}},
{name => q{nine}, type => q{c}},
);
my @tmpl = <DATA>;
my $t = HTML::Template->new(arrayref => \@tmpl);
$t->param(
{
M_OPTIONS => \@m_options
}
);
print $t->output;
__DATA__
<TMPL_LOOP M_OPTIONS>
name: <TMPL_VAR "name">
type: <TMPL_VAR "type">
</TMPL_LOOP>
patrial output:
name: one
type: a
name: two
type: b
name: three
type: c
The template is very simple and the data structure (an AoH) is _very_ similar to something you might get from the mighty DBI. :-)
If, again as the docs suggest, you carefully use TMPL_IF/UNLESS with H::T's loop context variables: __first__, __last__, __inner__, __odd__ and __counter__, you'll be able to produce very impressive HTML.
H::T is, imo, a fine example of doing one thing and doing it very well. Perl is very good at building and manipulating complex data structures. The two together are an excellent combination.
Did I say I like H::T? :-) |