in reply to Nirvana through the templating yin yang (TT2 /

Probably also obvious to those who've tried it, but you can do the same thing with HTML::Template. I realized it only very recently.

I originally had a drop-down list that I coded similar to:

<select name="the_thing"> <tmpl_loop name="select_thing"> <option value="<tmpl_var name="select_value">"> <tmpl_var name="select_tag"> </option> </tmpl_loop> </select>
(the values came out of a database lookup), but that lost the stickiness. I then realized I could cook up the select in CGI, and pass it to the template. So the only thing in the template file was just <tmpl_var name="the_whole_select">and I passed it the result of $q->popup_menu, and presto, stickiness returned. It's just a slight variation. (BTW, those samples are from memory, so there may be some inaccuracies in there.)

The nice thing about it is that all the "real" presentation stuff is still in the template; it's a lot more convenient than before, with a very slight loss of maintainability.

Replies are listed 'Best First'.
Re: Re: Nirvana through the templating yin yang (TT2 /
by thraxil (Prior) on Jun 18, 2003 at 15:37 UTC

    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:

    my $query = new CGI; my $template = HTML::Template->new(filename => 'template.tmpl', associate => $query);

    and a template variable is set for every param that CGI knows about.

    for selects, i still don't like to use $query->popup_menu. instead i have a function in a standard library that i use for all my web programming like so:

    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}]; }

    so in my code i can do:

    $template->param(some_loop => selectify(\@values,\@labels,[$query->par +am('some_param')]);

    and in the template:

    <select name="some_param"> <tmpl_loop name="some_loop"> <tmpl_include name="inner_loop.tmpl"> </tmpl_loop> </select>

    inner_loop.tmpl is factored out into its own template so i can reuse it all over the place. it just contains:

    <option value="<tmpl_var name="value" escape="html">"<tmpl_if name="se +lected"> selected="selected"</tmpl_if>><tmpl_var name="label" escape= +"html"></option>

    i don't know, i guess i just can't stand the thought of any of my output html being generated by and not totally controlled by my templates. that way if the designer wants to add a size, or class attribute to the select, they don't have to ask me to add it to the perl code.

    anders pearson