http://qs321.pair.com?node_id=312367

With the loop_context_vars switch in HTML::Template you can make some useful macros. I found myself needing things like this all too often:
$tmpl->param( foos => \@foo, num_foos => scalar @foo, bars => \@bar, num_bars => scalar @bar, ... );
So I made a macro that handles this inside the template by adding a <TMPL_NUM foo> directive. Does anyone else have useful HTML::Template tricks up their sleeves?

By the way, I'm well aware that this is a great example of the serious limits of templating using HTML::Template's philosophy. This is some ugly template-ese under the hood. This is why I will probably switch over to Template::Toolkit in the not-so-distant future (at least for projects where I'm the one writing the template).

use HTML::Template; sub tmpl_num_filter { s[<TMPL_NUM (\w+)>] [<TMPL_IF $1><TMPL_LOOP $1><TMPL_IF __LAST__><TMPL_VAR __COUNTER_ +_></TMPL_IF></TMPL_LOOP><TMPL_ELSE>0</TMPL_IF>]g for ${+shift}; } my $tmpl = HTML::Template->new( scalarref => \do { local $/; <DATA> }, filter => \&tmpl_num_filter, die_on_bad_params => 0, loop_context_vars => 1 ); $tmpl->param(hobbits => [ { name => "Frodo" }, { name => "Samwise" }, { name => "Meriadoc" } ]); print $tmpl->output; __DATA__ These are my <TMPL_NUM hobbits> favorite hobbits: <ul><TMPL_LOOP hobbits> <li><TMPL_VAR name> </TMPL_LOOP></ul>