feiiiiiiiiiii has asked for the wisdom of the Perl Monks concerning the following question:

Hi guys,

I'm using Template module for web programming. Everything works fine, except the keys and values keywords for hashes were not working as expected.

The variable I passed in is as below when dump print:

my $VARS = { 'rows' => { 'category1' => [ {'id' => 'AAA', 'delta' => '0.01%'}, {'id' => 'BBB', 'delta' => '0.03%'} ], 'category2' => [ {'id' => 'CCC', 'delta' => '0.02%'}, {'id' => 'DDD', 'delta' => '0.04%'} ], }, };

(The actual variable is much more complicated. I simplified it as above)

The code below works perfectly:

[% FOREACH item IN report.rows.category1 %] <tr> <td>[% item.id %]</td> <td>[% item.delta %] %</td> </tr> [% END %]

But the code below does not produce any entries:

[% FOREACH item IN report.rows.values %] <tr> <td>[% item.id %]</td> <td>[% item.delta %] %</td> </tr> [% END %]

Please note that the only difference between the above 2 code is "category1" vs "values"

The Template module version I'm using is 2.24. Not sure if it is because this is an older version that does not support keys & values keyword within % ... %

Anyone has any idea how I can fix it?

Thank you so much!!!

Replies are listed 'Best First'.
Re: Perl Template + html: hash keys and values keyword not working
by hippo (Archbishop) on May 07, 2016 at 21:59 UTC
    [% FOREACH item IN report.rows.values %] <tr> <td>[% item.id %]</td> <td>[% item.delta %] %</td> </tr> [% END %]

    The values of the report.rows hash are not themselves hashes, but arrays. Therefore item.id makes no sense. item.0.id is more likely to be what you are after.

    If you want to iterate over all items in the arrays you'll need a nested loop or some other means of iterating inside them. eg.

    #!/usr/bin/env perl use strict; use warnings; use Template; my $r = { 'rows' => { 'category1' => [ {'id' => 'AAA', 'delta' => '0.01%'}, {'id' => 'BBB', 'delta' => '0.03%'} ], 'category2' => [ {'id' => 'CCC', 'delta' => '0.02%'}, {'id' => 'DDD', 'delta' => '0.04%'} ], }, }; my $text = q# [% FOREACH item IN report.rows.values %] [% FOREACH one IN item %] <tr> <td>[% one.id %]</td> <td>[% one.delta %] %</td> </tr> [% END %] [% END %] #; my $tt = Template->new; $tt->process (\$text, {report => $r});

      Yes it is! Can't believe I'm making such a stupid bug :( It's working now. Thank you so much!

        Can't believe I'm making such a stupid bug

        We only make progress at anything worthwhile by making mistakes...

        That "doh!" we feel when we realise our mistake is actually out brain rewiring itself following an important moment of learning.