Re: [htmltmpl] Nested loop puzzle - variable columns and rows
Brought to you by:
samtregar
From: Roger B. W. <ro...@fi...> - 2004-02-11 13:28:52
|
On Wed, Feb 11, 2004 at 05:08:04AM -0800, LDT wrote: >The question is: how do I create my hash references to push into my loop in the correct order so that when I loop through my template, it all appears in the correct column? I've been able to successfully loop through a structure that has fixed columns and fixed rows, but this one is puzzling me and I don't know where to start. My approach would be to remodel the data into a fixed format, if there are few enough data that you can get away with holding them in memory twice (which for an HTML page you probably can). Also, while I used to use the named hash variable method that's in the example (%r1, %r2, etc.), these days I tend to use an explicitly anonymous hash because I find it more intuitive. So here's some (untested) code which should do what I think you want: my %data; my %account; my %month; # do database query here while (my $account,$description,$month,$amount)=$sth->fetchrow_array) { $data{$account}{$month}=$amount; $account{$account}=$description; $month{$month}=1; # gives us a list of "active" months } my @months=sort {$a <=> $b} keys %month; # or just my @months=(1..12); if you prefer my @accounts=sort {$a <=> $b} keys %account; my @ol; foreach my $account (@accounts) { my @il; my $total=0; foreach my $month (@months) { # use an empty space if no data are available push @il,{amount => $data{$account}{$month} || ''}; $total+=$data{$account}{$month}; } push @ol,{account => $account, description => $account{$account}, total => $total, month => \@il} } $tmpl->param(accounts => \@ol); which would go with a template something like: <tmpl_loop name=accounts> <tr><td><tmpl_var name=account></td> <td><tmpl_var name=description></td> <tmpl_loop name=month> <td>$<tmpl_var name=amount></td></tr> </tmpl_loop> <td>$<tmpl_var name=total></td></tr> </tmpl_loop> You'd generate the table headers separately (perhaps based on the content of @months), and probably use sprintf() for formatting the numbers, but I think that's the core of what you're after. Hope this helps, Roger |