Calling external modules in the Template Toolkit without plugins?

I am trying to call a Perl plug-in in a .ttfile Toolkit. The module I want to use is Util , and I want to call Util::prettify_date . I was able to enable this module using the Template Toolkit plug-in module: I configured the download, new, and error functions (as described here: http://template-toolkit.org/docs/modules/Template/Plugin.html ) and enable it using [% USE Util %] .

It works fine, but I was wondering, is there any way USE the Perl-modules in the Template Toolkit without needing to connect to them. The main problem with creating plugins is that I need to make all functions in Util object-oriented (i.e., taking $ self as the first argument), which does not really make sense.

+4
source share
2 answers

Have you tried use module in the [% PERL %] block?

Now I will personally write a plugin that passes, say, MyOrg::Plugin::Util->prettify_date to Util::prettify_date , after getting rid of the first argument. You can also automate the creation of these methods:

 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; } 
+6
source

You can also pass functions (i.e. routines) to the template as follows:

 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 produce the following:

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

All Articles