Middle-Earth Monks,

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:

foreach $key_1 (keys %hash_1) { foreach $key_2 (keys %hash_2) { $my_hash{$key_1}{$key_2} = something; } } ........ $vars = { my_hash= > \%my_hash }
Template snippet:
[% FOREACH key_1 IN my_hash.keys.sort.reverse %] [% FOREACH key_2 IN my_hash.$key_1.keys.sort.reverse %] output something [%END%] [%END%]
And everything is hunkey-dorey. Until, that is, some genius says "I could provide a button to reverse the sort order of the output."

EASY!, You say. Just remove the "reverse", like this:

[% FOREACH key_1 IN my_hash.keys.sort %] [% FOREACH key_2 IN my_hash.$key_1.keys.sort %] output something [%END%] [%END%]
Ya, but then I have to do something like
[% 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%]
Which is really clunky and doubles maintenace, which is in turn a pain when "output something" represents a couple hundred lines of mark-up.

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.




Time flies like an arrow. Fruit flies like a banana.

In reply to Reverse sort order in FOREACH in Template Toolkit by punch_card_don

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.