1

是否可以在加载时轻松修改模板(模板工具包),然后将其缓存为 Perl 代码?我想在它上面运行一个正则表达式。

4

2 回答 2

5

您可以提供自己的Template::Provider子类化标准模板。来自精美手册:

Template::Provider 用于加载、解析、编译和缓存模板文档。这个对象可以被子类化以提供更具体的加载工具,或者提供对模板的访问。

所以,它应该很容易但容易,当然,很大程度上取决于你的技能。

于 2010-12-15T01:09:07.680 回答
4

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.

于 2010-12-15T12:32:58.170 回答