------------------------------------------------------------------------
--------
From: Subbu Meiyappan
Sent: Wednesday, June 21, 2006 3:04 AM
To: [email protected]
Subject: [Templates] How to create Tied hashes?
>
> Probably an asked question: How do I create a tied hash so that when I
> retrieve the keys, I get it back in the order I inserted inside of
> TT2?. Example:
>
> [% hash = {
> one = 1,
> two = 2,
> three = 3
> };
> %]
>
> [% FOREACH key IN hash.list('keys');
> "$key\n";
> END;
> %]
>
> I'd like it to print
> one
> two
> three
>
> every time, deterministically. In regular perl, we use Tied hashes to
> achieve this effect. How do I do this TT? Obviously, I don't want to
> use the sort method, since my keys are random.
If you are using TT2 along with Perl (i.e. not via tpage) you can create
a
function to generate a tied hash for you, which you would then call from
TT2:
# perl script
use Template;
$Template::Config::STASH = 'Template::Stash';
sub make_ixhash {
use Tie::IxHash;
tie my %indexed, 'Tie::IxHash';
return \%indexed;
}
my $template = Template->new;
$template->process('template.tt2', { make_ixhash => \&make_ixhash })
|| die $template->error;
# template
[% hash = make_ixhash() %]
[% hash.one = 1 %]
[% hash.two = 2 %]
[% hash.three = 3 %]
[% hash.keys.join(',') # "one,two,three" %]
I just tested this and it works with the Perl (slow) stash, but does NOT
work with the XS stash (as of version 2.14, anyway).
Another solution would be to create an object wrapper that implements
the
TT2 hash vmethod interface, or at least the parts you need
(keys,each,etc.).
Philip
_______________________________________________
templates mailing list
[email protected]
http://lists.template-toolkit.org/mailman/listinfo/templates