note
thraxil
<p>HTML::Template also makes it easy and clean to make other form elements sticky. it lets you just associate the CGI object with the template:</p>
<code>
my $query = new CGI;
my $template = HTML::Template->new(filename => 'template.tmpl',
associate => $query);
</code>
<p>and a template variable is set for every param that CGI knows about.</p>
<p>for selects, i still don't like to use <tt>$query->popup_menu</tt>. instead i have a function in a standard library that i use for all my web programming like so:</p>
<code>
sub selectify {
my $values = shift;
my $labels = shift;
my $selected = shift;
my %selected = map {$_ => 1} @{$selected};
return [map {
{
value => $_,
label => shift @{$labels},
selected => $selected{$_} || "",
}
} @{$values}];
}
</code>
<p>so in my code i can do:</p>
<code>
$template->param(some_loop => selectify(\@values,\@labels,[$query->param('some_param')]);
</code>
<p>and in the template:</p>
<code>
<select name="some_param">
<tmpl_loop name="some_loop">
<tmpl_include name="inner_loop.tmpl">
</tmpl_loop>
</select>
</code>
<p><tt>inner_loop.tmpl</tt> is factored out into its own template so i can reuse it all over the place. it just contains:</p>
<code>
<option value="<tmpl_var name="value" escape="html">"<tmpl_if name="selected"> selected="selected"</tmpl_if>><tmpl_var name="label" escape="html"></option>
</code>
<p>i don't know, i guess i just can't stand the thought of any of my output html being generated by CGI.pm and not totally controlled by my templates. that way if the designer wants to add a <tt>size</tt>, or <tt>class</tt> attribute to the select, they don't have to ask me to add it to the perl code.</p>
<p align="right"><a href="http://www.columbia.edu/~anders/">anders pearson</a></p>
266830
266855