2009-08-16 55 views
4

我想在模板工具包.tt文件中调用外部Perl模块。我想要使​​用的模块是Util,我想打电话给Util::prettify_date。我能够使用Template Toolkit的插件接口包含这个模块:我设置了加载,新建和错误功能(如此处所述:http://template-toolkit.org/docs/modules/Template/Plugin.html),并使用[% USE Util %]包含它。在没有插件的模板工具包中调用外部模块?

这工作正常,但我想知道是否有一种方法USE模板工具包中的Perl模块,而无需插件 - 如果他们。制作插件的主要问题是我必须在面向对象(即接受$ self作为第一个参数)中使用Util中的所有函数,这没有任何意义。

回答

6

您是否尝试过在[% PERL %]块中使用use模块?

现在,我个人会写一个插件,例如,MyOrg::Plugin::Util->prettify_dateUtil::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; 
} 
14

您也可以通过功能(即子程序)到模板是这样的:

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(@_) }, 
}); 


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) %] 


will produc e此:

 
======================================== 
Hello my name is Barry, how are u today? 
The ultimate answer to life is 42 
========================================