[Belfast-pm] Template Toolkit, passing in a hash?

Tony Bowden tony at kasei.com
Tue Jul 6 05:06:53 CDT 2004


On Tue, Jul 06, 2004 at 10:21:39AM +0100, Simon McCartney wrote:
> I've been playing with TT on Debian, I've used it to prototype some stuff
> using DBI calls in the template, but I want to move to the next level.
> (I'm using Apache, MySQL & have the handler registered etc)
> 
> I have a couple of routines that generate a hash of information, and I want
> to display these in the processed template.
> 
> My understanding is that I would pass the hash in using $vars in the
> process method. But this means that the calculations take place for every
> page served by that handler, hardly efficient.
> 
> My next option would be to pass the subroutine in and only call it when
> needed in the template.  But this means changing my handler everytime I
> want to add a new subroutine to the module.
> 
> Is there a better way? Am I missing something?

You can pass in subrefs:

	#!/usr/bin/perl

	use strict;
	use warnings;

	use Template;

	my $tt = Template->new();
	$tt->process(\*DATA, {
		foo => sub { 1 + 2 },
		bar => sub { 3 ** 8 },
	});

	__DATA__
	[% foo %]
	[% bar %]


However, this is probably not what you really want to be doing. Without
more information though, we probably won't know the better way.

If you're doing DBI stuff with TT, you might want to look at Class::DBI,
which plays very nicely with TT...

Tony





More information about the Belfast-pm mailing list