Calling outside subs and modules in Template Toolkit without Plugins?

自作多情 提交于 2019-11-30 17:07:43

问题


I am trying to call an outside Perl module in a Template Toolkit .tt file. The module I want to use is Util, and I want to call Util::prettify_date. I was able to include this module using Template Toolkit's plugin interface: I set up the load, new, and error function (as described here: http://template-toolkit.org/docs/modules/Template/Plugin.html), and include it using [% USE Util %].

This works fine, but I was wondering if there's a way to USE Perl modules in Template Toolkit without having to plugin-ify them. The main issue with making plugins is that I have to make all the functions in Util object-oriented (ie. accepts $self as first argument), which doesn't really make sense.


回答1:


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

Now, I personally would write a plugin which relays, say, a MyOrg::Plugin::Util->prettify_date to Util::prettify_date after getting rid of the first argument. You can automate the creation of these methods as well:

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;
}



回答2:


You can also pass functions (ie. subroutines) to template like this:

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 this:

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


来源:https://stackoverflow.com/questions/1285441/calling-outside-subs-and-modules-in-template-toolkit-without-plugins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!