Sam*_*Lee 5 perl template-toolkit
我试图在Template Toolkit .tt文件中调用外部Perl模块.我想要使用的模块是Util,我想打电话Util::prettify_date.我能够使用Template Toolkit的插件接口包含这个模块:我设置了load,new和error函数(如下所述:http://template-toolkit.org/docs/modules/Template/Plugin.html),并使用它包括它[% USE Util %].
这工作正常,但我想知道是否有一种方法可以USE在Template Toolkit中使用Perl模块而无需插件 - 如果它们.制作插件的主要问题是我必须使用Util面向对象的所有函数(即接受$ self作为第一个参数),这实际上没有意义.
dra*_*tun 15
您还可以将函数(即子例程)传递给模板,如下所示:
use strict;
use warnings;
use List::Util ();
use Template;
my $tt = Template->new({
INCLUDE_PATH => '.',
});
$tt->process( 'not_plugin.tt', {
divider => sub { '=' x $_[0] },
capitalize => sub { ucfirst $_[0] },
sum => sub { List::Util::sum( @_ ) },
});
Run Code Online (Sandbox Code Playgroud)
not_plugin.tt
[% divider( 40 ) %] Hello my name is [% capitalize( 'barry' ) %], how are u today? The ultimate answer to life is [% sum( 10, 30, 2 ) %] [% divider( 40 ) %]
会产生这个:
======================================== Hello my name is Barry, how are u today? The ultimate answer to life is 42 ========================================
您是否尝试use过模块[% PERL %]?
现在,我个人会写一个插件,在断开第一个参数之后MyOrg::Plugin::Util->prettify_date继续传递Util::prettify_date.您也可以自动创建这些方法:
my @to_proxy = qw( prettify_date );
sub new {
my $class = shift;
{
no strict 'refs';
for my $sub ( @to_proxy) {
*{"${class}::${sub}"} = sub {
my $self = shift;
return "My::Util::$sub"->( @_ );
}
}
}
bless {} => $class;
}
Run Code Online (Sandbox Code Playgroud)