[Templates] How to create Tied hashes?

Garrett, Philip (MAN-Corporate) Philip.Garrett@manheim.com
Wed, 21 Jun 2006 08:27:18 -0400


------------------------------------------------------------------------
--------
From: Subbu Meiyappan
Sent: Wednesday, June 21, 2006 3:04 AM
To: templates@template-toolkit.org
Subject: [Templates] How to create Tied hashes?
>=20
> 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:
>=20
> [% hash =3D {
>         one =3D 1,
>         two =3D 2,
>         three =3D 3
>        };
> %]
>=20
> [% FOREACH key IN hash.list('keys');
>      "$key\n";
>      END;
> %]
>=20
> I'd like it to print
> one
> two
> three
>=20
> 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.
=20
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:
=20
  # perl script

  use Template;
  $Template::Config::STASH =3D 'Template::Stash';
 =20
  sub make_ixhash {
      use Tie::IxHash;
      tie my %indexed, 'Tie::IxHash';
      return \%indexed;
  }
  my $template =3D Template->new;
  $template->process('template.tt2', { make_ixhash =3D> \&make_ixhash })
      || die $template->error;
 =20
  # template
 =20
  [% hash =3D make_ixhash() %]
  [% hash.one   =3D 1       %]
  [% hash.two   =3D 2       %]
  [% hash.three =3D 3       %]
=20
  [% hash.keys.join(',')  # "one,two,three" %]
=20
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).
=20
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.).
=20
Philip