FloydATC has asked for the wisdom of the Perl Monks concerning the following question:
Given an array of hashes, I want to use Template Toolkit to loop through the array sorted by a hash key 'name':
my @array = ( { name => 'foo', value => 1 }, { name => 'bar', value => 2 }, { name => 'baz', value => 3 } );
[% FOREACH element IN array.sort('name') %] [% element.name %] [% END %]
This works ok if @array has zero or more than 1 member.
However, if @array has exactly 1 member, the virtual method "sort()" will instead return the contents of that one hash in alphabetical order. Needless to say, this causes the output to be completely wrong since "element.name" will now render as a series of empty strings because they will be undefined.
Obviously, there is no need to sort an array with only one member, but in actual use I have no way of knowing in advance how many members there will be.
Does anyone know of a known fix/workaround for this problem? How can I tell Template that "array" is in fact an array?
Update:I found a workaround that seems to do the trick:
[% PERL %] my $copy; @{$copy} = $stash->get('array'); if (ref($copy) eq 'ARRAY') { $stash->set('copy', sort { $a->{'name'} cmp $b->{'name'} } @{$copy}) +; } [% END %] [% FOREACH element IN copy %] [% element.name %] [% END %]
Time flies when you don't know what you're doing
|
|---|