Associate table cell with header
I want to associate a cell value in table with it's header. The header is not known, as it was generated by SQL query.
Sizes as header came from SQL return result. So then put it into an array,
@sizes = qw(S36 S37 S38 S39 S40 S41 S42);
Now, if James has size S38.
I want to print them as HTML table with sizes header:
+--------+--------+--------+-------+-------+-------+-------+
| S36 | S37 | S38 | S39 | S40 | S41 | S42 |
+--------+--------+--------+-------+-------+-------+-------+
| | | James | | | | |
+--------+--------+--------+-------+-------+-------+-------+
I know how to do this if sizes is part of row or result, but as table header?
How to manipulate this with Perl?
EDITED:
I try to summarize the code i tried...
SQL query:
select size from articles where order_number = "3";
Get into an array:
while(my $ref = $sth->fetchrow_hashref()) {
$size = "$ref->{'size'}";
push @sizes, $size;
}
Say, @sizes
is:
@sizes = qw(S36 S37 S38 S39 S40 S41 S42);
Create HTML header based on sizes:
+--------+--------+--------+-------+-------+-------+-------+
| S36 | S37 | S38 | S39 | S40 | S41 | S42 |
+--------+--------+--------+-------+-------+-------+-------+
Now, say from another SQL query, i know that James has S38. How to put into the right row cell of the above table. It would be:
+--------+--------+--------+-------+-------+-------+-------+
| S36 | S37 | S38 | S39 | S40 | S41 | S42 |
+--------+--------+--------+-------+-------+-------+-------+
| | | James | | | | |
+--------+--------+----开发者_StackOverflow社区----+-------+-------+-------+-------+
Here is a way of doing it using CGI.pm HTML generation methods:
#!/usr/bin/perl
use strict;
use warnings;
use CGI qw(:html);
use List::AllUtils qw( first_index );
my @sizes = qw(S36 S37 S38 S39 S40 S41 S42);
my %person = ( name => 'James', size => 'S38');
my @row = ('') x @sizes;
$row[ first_index { $_ eq $person{size} } @sizes ] = $person{name};
print start_html,
table( { border => 1 },
Tr(td({width => sprintf('%.0f%%', 100/@sizes)}, \@sizes)),
Tr(td(\@row) ) ),
end_html;
On the other hand, I do love HTML::Template:
#!/usr/bin/perl
use strict; use warnings;
use HTML::Template;
use List::AllUtils qw( first_index );
my @sizes = qw(S36 S37 S38 S39 S40 S41 S42);
my %person = ( name => 'James', size => 'S38');
my @row = (' ') x @sizes;
$row[ first_index { $_ eq $person{size} } @sizes ] = $person{name};
my $tmpl_txt = <<EO_TMPL;
<html><head><style type="text/css">
#size_chart { margin: 0 auto; }
#size_chart td { width: <TMPL_VAR CELL_WIDTH>; border: 2px inset #ddd }
</style></head>
<body><table id="size_chart">
<TMPL_LOOP ROWS><tr>
<TMPL_LOOP CELLS><td><TMPL_VAR CELL></td></TMPL_LOOP>
</tr></TMPL_LOOP>
</table></body></html>
EO_TMPL
my $tmpl = HTML::Template->new(scalarref => \$tmpl_txt);
$tmpl->param(
CELL_WIDTH => sprintf('%.0f%%', 100/@sizes),
ROWS => [ { CELLS => [ map { { CELL => $_ } } @sizes ] },
{ CELLS => [ map { { CELL => $_ } } @row ] },
]);
print $tmpl->output;
精彩评论