Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-04-19 23:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found