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>

In reply to HTML::Template macros by blokhead

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.