[cgiapp] Variable Number of Column in a Table

Cees Hek ceeshek at gmail.com
Thu May 15 19:40:00 EDT 2008


On Fri, May 16, 2008 at 2:03 AM, Stephen Carville
<stephen.carville at gmail.com> wrote:
> Is there any way to have a template where the number of columns is
>  determined at run time?  I know how to use TMPL_LOOP but that only
>  lets me vary the number of rows.

I realize that you are using HTML::Template, and you may be tied to it
for reasons good or bad, but
whenever I see people trying to bend a tool to do things against it's
will I feel obliged to show another way ;)

In my example below, the data is provided in a format that is easy to
generate using a DBI call, and the template itself is pretty straight
forward.  Row colouring is also made easy using the Cycle plugin (if
you want to alternate between three colours, just add another entry
into the cycle and leave the rest of the template as is).

use Template;

my $template = Template->new( POST_CHOMP => 1 );
my $data = {
    headers => [qw(col1 col2 col3 col4)],
    rows    => [
        [ qw(1.1 1.2 1.3 1.4) ],
        [ qw(2.1 2.2 2.3 2.4) ],
        [ qw(3.1 3.2 3.3 3.4) ],
        [ qw(4.1 4.2 4.3 4.4) ],
        [ qw(5.1 5.2 5.3 5.4) ],
        [ qw(6.1 6.2 6.3 6.4) ],
    ],
};
$template->process(\*DATA, $data) or die $template->error;
__END__
[% USE rowclass = Cycle('oddclass', 'evenclass') %]
<table>
 <tr>
[% FOREACH col IN headers %]
  <th>[% col %]</th>
[% END %]
 </tr>
[% FOREACH row IN rows %]
 <tr class="[% rowclass %]">
[%   FOREACH col IN row %]
   <td>[% col %]</td>
[%   END %]
 </tr>
[% END %]
</table>


Cheers,

Cees


More information about the cgiapp mailing list