On Tue, 30 Sep 2003, Tony Bowden wrote:

> I have a hash of ( id => name ) pairs, from which I want to create a CGI
> checkbox group:
> 
>   CGI.checkbox_group('team', team.keys, 1, 1, team).join
> 
> However, I'd like to sort the output of hash.keys - but by the names of
> the teams, not their IDs.
> 
> In perl this would be sort { $team{$a} cmp $team{$b} } keys %team, but I
> can't work out how to do this sort of thing in TT. I'm guessing that
> it's a common enough thing that there must be an idiom for it, but I'll
> feeling particularly slow today ...

Tony,

I don't know of any idiom use native TT2 virtual methods, but this
is an example of how I do it:



#!/usr/bin/perl

use strict;
use Template;
use Template::Stash;

$Template::Stash::HASH_OPS->{ keys_vsort } =
 sub {
  my ($hash) = @_;
  return [ sort { $hash->{$a} cmp $hash->{$b} } keys %{$hash} ];
 };

my $tt2 = new Template;
$tt2->process(\*DATA);

__DATA__
[%- hash = { '1' => 'Camille',
             '2' => 'Andrew',
             '3' => 'Lili',
             '4' => 'Isidore' } %]
[%- FOREACH key IN hash.keys_vsort %]
[%-     key %] = [% hash.$key %]
[% END %]



It would be nice to be able to do something like 

  hash.keys.vsort

but I don't know of a way to refer to 'hash' from within a LIST_OPS
vmeth, which 'vsort' would have to be.  That's why I ended up with
the HASH_OPS vmeth named the way I named it.

Hope that helps.

Dave

/L\_/E\_/A\_/R\_/N\_/T\_/E\_/A\_/C\_/H\_/L\_/E\_/A\_/R\_/N\
Dave Cash                              Power to the People!
Frolicking in Fields of Garlic               Right On-Line!
[EMAIL PROTECTED]                                  Dig it all.


_______________________________________________
templates mailing list
[EMAIL PROTECTED]
http://lists.template-toolkit.org/mailman/listinfo/templates

Reply via email to