punch_card_don has asked for the wisdom of the Perl Monks concerning the following question:
So you're using Temlpate Toolkit and you've got a list to output and you've stored that list in a multi-dimension hash and you output it like this:
Perl script snippet:
Template snippet:foreach $key_1 (keys %hash_1) { foreach $key_2 (keys %hash_2) { $my_hash{$key_1}{$key_2} = something; } } ........ $vars = { my_hash= > \%my_hash }
And everything is hunkey-dorey. Until, that is, some genius says "I could provide a button to reverse the sort order of the output."[% FOREACH key_1 IN my_hash.keys.sort.reverse %] [% FOREACH key_2 IN my_hash.$key_1.keys.sort.reverse %] output something [%END%] [%END%]
EASY!, You say. Just remove the "reverse", like this:
Ya, but then I have to do something like[% FOREACH key_1 IN my_hash.keys.sort %] [% FOREACH key_2 IN my_hash.$key_1.keys.sort %] output something [%END%] [%END%]
Which is really clunky and doubles maintenace, which is in turn a pain when "output something" represents a couple hundred lines of mark-up.[% IF sort_order == 1 %] [% FOREACH key_1 IN my_hash.keys.sort %] [% FOREACH key_2 IN my_hash.$key_1.keys.sort %] output something [%END%] [%END%] [% ELSE %] [% FOREACH key_1 IN my_hash.keys.sort.reverse %] [% FOREACH key_2 IN my_hash.$key_1.keys.sort.reverse %] output something [%END%] [%END%] [%END%]
SOOOOOOO - I'm looking for what you might call a "conditional foreach" statement. Some way to reverse the sort order of a single foreach.
[% FOREACH key_1 IN my_hash.keys.variable_sort_order %] [% FOREACH key_2 IN my_hash.$key_1.keys.variable_sort_order %] output something [%END%] [%END%]
Does such an animal exist?
Thanks.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Reverse sort order in FOREACH in Template Toolkit
by Herkum (Parson) on Apr 15, 2009 at 22:06 UTC | |
by punch_card_don (Curate) on Apr 16, 2009 at 02:07 UTC | |
by Herkum (Parson) on Apr 16, 2009 at 03:00 UTC | |
|
Re: Reverse sort order in FOREACH in Template Toolkit
by Fletch (Bishop) on Apr 15, 2009 at 22:12 UTC | |
|
Re: Reverse sort order in FOREACH in Template Toolkit
by CountZero (Bishop) on Apr 15, 2009 at 22:08 UTC | |
|
Re: Reverse sort order in FOREACH in Template Toolkit
by holli (Abbot) on Apr 16, 2009 at 09:40 UTC |