Re: Using a "hash" as a Template::Provider
Stuart A Johnston <[email protected]> Thu, 14 Mar 2013 20:58:16 -0500
| Newsgroups | gmane.comp.lang.perl.modules.template-toolkit |
|---|---|
| Message-ID | <[email protected]> |
You'll probably need to override the 'fetch' method in your subclass if
your hash keys are not sufficiently 'filename like'.
Template::Provider::DBI should be a good example.
As for the name, I'd consider Template::Provider::HASH.
On 03/14/2013 08:13 PM, Philippe Bruhat (BooK) wrote:
> Hi,
>
> For a $work project, I'm basically building a hash of
> template text, and want to be able to reference those
> from my templates.
>
> So I came up with this Template::Provider subclass:
>
>
> package Template::Provider::FromText;
>
> use strict;
> use warnings;
>
> use Template::Provider;
> our @ISA = qw( Template::Provider );
>
> sub _template_modified { $^T }
>
> sub _template_content {
> my ( $self, $path ) = @_;
> $path =~ s{^\./}{}; # INCLUDE_PATH = ./
>
> my $data = $self->{TEMPLATE_BY_NAME}{$path};
> my $mod_date = $^T;
> my $error =
> $path
> ? defined $data
> ? ''
> : "$path: template not found"
> : "No path specified to fetch content from";
>
> return wantarray ? ( $data, $error, $mod_date ) : $data;
> }
>
> sub add {
> my ( $self, %template ) = @_;
> @{ $self->{TEMPLATE_BY_NAME} }{ keys %template } = values %template;
> return $self;
> }
>
> 1;
>
> which I then use like this:
>
> # a hash of name => template_text
> my %template = (
> t1 => '[% INCLUDE t2 %]',
> t2 => '[% foo %]',
> );
> my $template = Template->new(
> LOAD_TEMPLATES => [ Template::Provider::FromText->new->add(%template) ]
> );
>
> I was disappointed to not be able to do:
>
> $template->process( 't1', $vars ); # expects t1 to be a file name
>
> However, this worked just fine:
>
> $template->process( \$template{t1}, $vars );
>
>
>
> My question is: did I overlook a simpler way to do this?
>
> And if not, has anyone a better name than Template::Provider::FromText
> to propose, before I put something like the above (with documentation,
> and a better _template_modified)?
>
> Thanks,
>