[htmltmpl] Select/option lists (how to generate)
Brought to you by:
samtregar
From: Mark A. F. <mar...@ea...> - 2005-01-10 16:24:36
|
>What I'm currently using is this method > > <input name="my_input_box"<TMPL_IF NAME="my_input_box_value"> > value="<TMPL_VAR NAME="my_input_box_value">"</TMPL_IF>> I don't believe you need the conditional. You can let "my_input_box_value" evaluate always. If it contains nothing, it will evaluate to nothing. Your template won't be as cluttered. >However, how can this be done for select boxes (drop-down lists)? This was the thing that was the most difficult for me. I thought H::T should have a mechanism to handle this more directly. What I do is loop selecting my values from a database into a hash (using DBI "fetch"). ======================================= while ($sth_select_some_list->fetch) { # %db_vals is automatically populated because the prepared statement # has "bind_col" each column to a $db_vals{key}. if ($db_vals{code} eq $selected_value) { $sel = ' selected="selected"'; } else { $sel = ''; } push @loop_data, { VAL => $db_vals{code}, TEXT => $db_vals{display}, SELECTED => $sel, LANG => ' lang="en"' } } # end loop $template->param(MY_LOOP => \@loop_data); ================================== And then the template looks like this: ================================== <select id="my_list" name="my_list"> <TMPL_LOOP NAME=MY_LOOP><option value="<TMPL_VAR NAME=VAL>"<TMPL_VAR NAME=SELECTED>><TMPL_VAR NAME=TEXT></option></TMPL_LOOP> </select> ================================== A few months ago someone posted a nifty SQL select that created the array to be passed to the template (all in one SQL). I actually do a one-time select into a hash, and regenerate the select list with each display. I do this because I translate the values selected from a table into whatever language the visitor chose. I don't want to do that with each display. So, I select and translate when I detect the first time the page will be displayed in that language. I generate the select list from a those values which I keep in memory as long as my script is in memory. This gets back to how I wish there was a way to perform evaluation upon the cached H::T template. I could evaluate the select list values with the language. And then only evaluate the "selected" attribute for each display. Mark |