Re: [Templates] multilevel hash to table, plus bonus question
[prev]
[thread]
[next]
[Date index for 2004/09/03]
On Fri, 3 Sep 2004, Jamie Echlin wrote:
> Thanks for the response Dave.
You're welcome.
> > This is something you'd have a hard time doing even in Perl.
>
> Hmm, I thought maybe TT would make it easy for me by not treating "A.B"
> as a hash key but as two keys, but I guess yep, I am asking the
> impossible, or the unlikely at least.
If I understand the internals correctly, the problem is that by the
time TT2 (or Perl, for that matter) is looking to see what $col is
set to, it's already done parsing syntax and assumes it will only
find a variable value inside, not more syntax. Thus, eval.
> Next qn: Sometimes my API returns an IxHash, ie an ordered hash. When
> this happens I cannot use the hash virtual methods, although they all
> make logical sense. IxHash has methods like Keys Values similar to the
> vmethods, but the case is different. Any ideas here?
The only simple way I can think of to handle this is to do something
like this:
----------------------------------------------------------------------
#!/usr/bin/perl
use strict;
use warnings;
use Tie::IxHash;
use Template;
my @list = ( id => '68000', name => 'Steve', phone => '555-6502' );
my $data = {
hashes => [
{ @list },
new Tie::IxHash( @list )
]
};
my $tt = new Template or die $Template::ERROR;
$tt->process( \*DATA, $data ) or die $tt->error;
__DATA__
[%- FOREACH hash IN hashes -%]
[%- IF hash.can( 'Keys' ) -%]
[%- FOREACH key IN hash.Keys %]
<td>
[% key %] = [% hash.Values( key ) %]
</td>
[%- END %]
[%- ELSE -%]
[%- FOREACH key IN hash.keys %]
<td>
[% key %] = [% hash.$key %]
</td>
[%- END %]
[%- END -%]
[%- END %]
----------------------------------------------------------------------
but that gets a little messy since you have to repeat your
table-cell drawing code. Perhaps in cobmination with a MACRO to
draw the contents of a cell, this would be a better solution.
I'm sure there are other options, but since one thing is a hash ref
and one is an object ref, it makes things a bit sticky.
Take care,
Dave
/L\_/E\_/A\_/R\_/N\_/T\_/E\_/A\_/C\_/H\_/L\_/E\_/A\_/R\_/N\
Dave Cash Power to the People!
Frolicking in Fields of Garlic Right On-Line!
dave@xxxxx.xxx Dig it all.
_______________________________________________
templates mailing list
templates@xxxxxxxxxxxxxxxx.xxx
http://lists.template-toolkit.org/mailman/listinfo/templates