C. Chad Wallace wrote:
> At 11:58 AM on 09 Mar 2010, Josh Stompro wrote:
>
>
>> I have tried to do some sorting of the hash using the sort virtual
>> method, but I don't think it can handle what I am looking to do.
>>
>> [% FOREACH item IN items.sort %]
>> [% item %]
>> [% items.$item.value %]
>> [% items.$item.call %]
>> [% END %]
>> This should sort based on the items keys, but that doesn't seem to
>> work in any case. Is there any way to sort based on a sub hash value
>> of the elements returned. Or should I reformat my data so that the
>> key is the value I want to sort on?
>>
>
> Try this (in your perl, prior to your Template->new and ->process
> calls):
>
> use Template ();
> use Template::Stash ();
>
> # subsort - sort the hash's keys by the values of a key in
> # subordinate hashes.
> $Template::Stash::HASH_OPS->{ subsort } = sub {
> my ($hash, $key) = @_;
> [ sort { lc $hash->{$a}->{$key} cmp lc $hash->{$b}->{$key} }
> (keys %$hash)
> ];
> };
>
>
> That defines a new VMethod for sorting, so you can do this in your
> template:
>
> [% FOREACH item IN items.subsort( 'call' ) %]
> [% item %]
> [% items.$item.value %]
> [% items.$item.call %]
> [% END %]
>
>
> This is totally untested... please let me know if it works. :-)
>
>
> PS, you say that 'items.sort' should sort "based on the items keys",
> but it doesn't. For that, you would use 'items.keys.sort'.
> 'items.sort' sorts the keys based on their corresponding values in the
> hash (all of which, in this case, are hash references and are probably
> not useful for sorting).
>
>
Chad, that was just the tip I needed. Thank you very much. I modified
it to take two sort keys and now it is working just like I need.
$Template::Stash::HASH_OPS->{ subsort } = sub {
my ($hash, $key1, $key2) = @_;
[ sort { lc $hash->{$a}->{$key1} cmp lc $hash->{$b}->{$key1} || lc
$hash->{$a}->{$key2} cmp lc $hash->{$b}->{$key2} }
(keys %$hash)
];
};
[% FOREACH item IN items.subsort( 'call' , 'author' ) %]
Thank you also for correcting me on what the .sort virtual method is
sorting on by default.
Josh
_______________________________________________
templates mailing list
[email protected]
http://mail.template-toolkit.org/mailman/listinfo/templates