Using Tempalte Toolkit's 'foreach' to output the contents of a hash into a table, where the key is numeric adn applying the sort operator to the keys. Well of course I'm getting an ascii-sort (1, 10, 11, 12, 2, 20, 21,...) instead of a numerical sort (1, 2, 3..., 9, 10, 11..., 19, 20, 21...)
In Perl, we can do
foreach $key (sort {$a <=> $b} keys %myhash) { do stuff; }
Is there any way to apply this kind of thing to the TT foreach loop?
Thanks.
Sample code:
Perl Script
$sql = "SELECT record_id, attribute_1, attribute_2 FROM theTable"; $sth = $dbh->prepare($sql) or die("Could not prepare!" . $dbh->errstr) +; $sth->execute() or die("Could not execute!" . $dbh->errstr); while ($record_id, $att_1, $att_2) = $sth->fetchrow_array()) { $data_hash{$record_id} = { att_1 => $att_1, att_2 => $att_2 }; } $vars = { data_hash => \%data_hash }; $template->process($template_file, $vars) || die "Template process failed: ", $template->error(), "\n";
Template:
<table class="myClass"> [% FOREACH record_id IN data_hash.keys.sort.reverse %] <tr><td>$data_hash.$record_id.att_1</td><td>$data_hash.$record_id +.att_2</td></tr> [% END %] </table>
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |