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,

-- 
 Philippe Bruhat (BooK)

 Virtue may not be its own reward but it's sure a lot easier to collect!!
                                  (Moral from Groo The Wanderer #3 (Pacific))

_______________________________________________
templates mailing list
templates@template-toolkit.org
http://mail.template-toolkit.org/mailman/listinfo/templates

Reply via email to