in reply to Re: Reverse sort order in FOREACH in Template Toolkit
in thread Reverse sort order in FOREACH in Template Toolkit

Well, I'm torn on this. I totally agree this sounds very sensible. Do the crunching in the Perl script.

But at the same time, this use of TT just seems custom made for my application, with th epossible exception of this last outrageous desire. I mean, imagine, you've got data that looks like

year x 5
- class x 3
--- sub-class x 5
----- data rows x 50

This just screams for

$data{$year}{$class}{$sub-class}{row-element-i} = 'foo';
and then
<table> [% FOREACH year IN data.keys.sort %] <tr><td colspan=x>Year [% year %]</td></tr> [% FOREACH class IN data.$year.keys.sort %] <tr><td>spacer</td><td colspan=x-1>Class [% class %]</td></tr> [% FOREACH sub-class IN data.$year.$class.keys.sort %] <tr><td colspan=2>spacer</td><td colspan=x-2>Sub-Class [% sub +-class %]</td></tr> <tr> [% FOREACH element IN data.$year.$class.$sub-class.keys.sort +%] <td>[% data.$year.$class.$sub-class.$element %]</td> [%END%] </tr> [%END%] [%END%] [%END%] </table>
and, bing!, you're done, with the data generation completely dissociated from the layout generation.

This is the kind of power that made me fall in love with TT.

My alternative - or at least the only one of which I'm aware, would be to do all that html generation inside the Perl script and export $data_table_html_string to the template.

Replies are listed 'Best First'.
Re^3: Reverse sort order in FOREACH in Template Toolkit
by Herkum (Parson) on Apr 16, 2009 at 03:00 UTC

    I am not saying you should move the HTML to a plugin, only the data-prep.

    Looking at your example, I would return a your data already sorted and have everything in arrays of objects. Loop through your arrays and your data will be easier to work with in TT. Example;

    [% USE MyPlugin; classifications = MyPlugin.classifications( data ); %] [% FOREACH year = classifications %] <tr><td colspan=x>Year [% year.no %]</td></tr> [% FOREACH class = year.classes %] <tr><td>spacer</td><td colspan=x-1>Class [% class %]</td></tr> [% FOREACH sub_class = class.sub_classes %] <tr><td colspan=2>spacer</td><td colspan=x-2>Sub-Class [% +sub_class %]</td></tr> <tr> [% FOREACH element = sub_class.elements %] <td>[% element %]</td> [% END %] [% END %] [% END %] [% END %]

    As you can see this is a lot cleaner than what you are doing. You can get away with not using objects by just setting a variable which is reference to the nested hash. You should really avoid having to type all this to get the data you want.

    FOREACH element IN data.$year.$class.$sub-class.keys.sort