我正在使用 Tpage(Template Toolkit 的命令行封装程序),documentation 描述了如何为标量、列表或哈希变量创建自定义虚拟方法,然后将它们作为 variable.custom_method()
调用。然而,我想在模板中定义一些独立的函数,可以直接使用。想法如下:
这是我的 functions.tt 文件:
[%- PERL -%]
sub int2hex{
my $intvar = shift;
return sprintf("%X", $intvar);
};
[%- END -%]
[% myInteger=18 %]
这是我的 template.tt 文件:
Some text
The value of [%myInteger%] in hexadecimal is [% int2hex(myInteger) %]
More text
然后我会从命令行调用模板工具包,如下所示:
tpage --eval_perl --pre_process=functions.tt template.tt > result.f
期望的是首先处理
function.tt
文件,使得int2hex()
子程序可以在template.tt
文件中使用。然而,我收到了一个错误,说undef error - int2hex is undefined
。另一方面,它并没有抱怨myInteger
。看起来文件的
[% PERL %][% END %]
部分没有将int2hex
函数添加到方法列表中。按照这里所述的方式,使用宏或插件实现这一点并不直观。有没有更简单的方法直接在模板文件中定义函数?