[Melbourne-pm] Looping with HTML::Template
Mathew Robertson
mathew.robertson at netratings.com.au
Mon Oct 27 15:30:52 PDT 2008
> Further to the thread about the sub called 'Strange things about '0'.
> I have the section of Perl below to build up an array of hashes that
> will get used by HTML::Template after sql_engine finishes.
> At the moment it is hardcoded to only produce 6 fields in the row.
>
> How do I make the .html file flexible so that in the Perl code I can
> replace the 6 with a variable like $Num_of_fields allowing me to
> choose at run time how wide the HTML table is?
> Or is there a different module/technique I should use to get this type
> of functionality?
>
> BTW: That 'FooCode' field below is where one of values of foocode from
> the other thread will appear and may get filtered on.
>
> sub sql_engine {
> .
> .
> .
> elsif ($ret_type eq 'array_hash') {
> my $cnt = 0;
> my @loop_data;
> while (my @data = $report->fetchrow_array) {
> my $cell = 0; # This number is used as a temp variable name
> in the .html file
> my %row_data; # use a hash to hold the data for each row
> that HTML::Template will display.
> # populate the hash.
> while ($cell < 6) {
> $row_data{$cell} = shift @data;
> $cell++; }
> push (@loop_data, \%row_data);
> $cnt++;
> }
> $report->finish();
> $dbh->disconnect;
> return \@loop_data; }
>
> Contents of the .html file
>
> <table border =1 cellpadding = 4 cellspacing =0>
> <tr>
> <th bgcolor =#fffbc6>Model</th>
> <th bgcolor =#fffbc6>Serial Number</th>
> <th bgcolor =#fffbc6>Customer Number</th>
> <th bgcolor =#fffbc6>Asset ID</th>
> <th bgcolor =#fffbc6>FooCode</th>
> <th bgcolor =#fffbc6>Standard Code</th>
> </tr>
> <TMPL_LOOP NAME='blankassets'>
> <tr>
> <td><TMPL_VAR name="0"></td>
> <td><TMPL_VAR name="1"></td>
> <td><TMPL_VAR name="2"></td>
> <td><TMPL_VAR name="3"></td>
> <td><TMPL_VAR name="4"></td>
> <td><TMPL_VAR name="5"></td>
> </tr>
> </TMPL_LOOP>
> </table>
The simplest solution (albeit, not elegant...) is that the template
needs to check if the TMPL_VAR is defined for that cell, as in:
<TMPL_LOOP ...>
<TMPL_IF name="0"><td><TMPL_VAR name=""></td></TMPL_IF>
... and so on...
</TMPL_LOOP>
Mathew
More information about the Melbourne-pm
mailing list