开发者

modification of TT template

开发者 https://www.devze.com 2023-01-30 09:34 出处:网络
Is it possible to easily modify template (Template Toolkit) when it 开发者_开发知识库is loaded, before it is cached as Perl code? I want to run a regular expression on it.You can supply your own Templ

Is it possible to easily modify template (Template Toolkit) when it 开发者_开发知识库is loaded, before it is cached as Perl code? I want to run a regular expression on it.


You can supply your own Template::Provider that subclasses the standard one. From the fine manual:

The Template::Provider is used to load, parse, compile and cache template documents. This object may be sub-classed to provide more specific facilities for loading, or otherwise providing access to templates.

So, it should be pretty easy but easy, of course, greatly depends on your skill.


The Template::Provider suggestion above is probably the best way to do it. But there's also a simpler (if slightly hacky) approach. You can read the template into a scalar and run whatever transformations on it that you want before passing it to the template processor.

my $tt = Template->new;

open my $template_fh, '<', 'template.tt' or die $!;
my $template = do { local $/; <$template_fh> };

$template =~ s/some regex/some replacement/;

my $vars = { template => 'variables' };

$tt->process(\$template, $vars) or die $tt->error;

The secret is that the process() method takes various types of value as its first parameter. If you give if a scalar then that's assumed to be the name of a file that contains the template. But if it's a reference to a scalar, then it assumes that that scalar contains the actual template. See the documentation for more details.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号