To make template a global you can do this:
use vars qw/$template/;
$template = undef;
#calls foo
foo()
#outputs page
print $template->output;
sub foo {
$template = HTML::Template->new(filename => 'test.tmpl');
# fill in some parameters in the template
$template->param(home => $ENV{HOME});
$template->param(path => $ENV{PATH});
}
or
our $template;
$template = undef;
#calls foo
foo()
#outputs page
print $template->output;
sub foo {
$template = HTML::Template->new(filename => 'test.tmpl');
# fill in some parameters in the template
$template->param(home => $ENV{HOME});
$template->param(path => $ENV{PATH});
}
Please note that I clear $template's value, since I assume we don't want to risk values survivng there between mod_perl base invocations. You may not be programming for mod_perl, but it is worthwhile to produce compatible code.
Maybe you should consider making a Page object and stashing a template reference there.
package Page;
use HTML::Template;
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
$self->setTemplate('default.tmpl');
return $self;
}
sub setTemplate {
my $self = shift;
my $file = shift;
# You really should validate the template filename here.
$self{template} = HTML::Template->new(filename => $file);
}
sub template {
my $self = shift;
return $self->{template};
}
sub output {
my $self = shift;
return $selft->template->output;
}
1;
Then your script would look like:
use Page;
my $p = Page->new;
$p->setTemplate('test.tmpl');
$p->template->param(home => $ENV{HOME});
$p->template->param(path => $ENV{path});
$p->output;
This way is nice because you don't rely on any globals, it is easy to write test scripts for your object, you can work with multiple templates at once, and you can store other interesting info in the page object.
TGI says moo
|