Calling outside subs and modules in Template Toolkit without Plugins?

后端 未结 3 1965
再見小時候
再見小時候 2020-12-31 20:54

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

相关标签:
3条回答
  • 2020-12-31 21:36

    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
    ========================================
    
    0 讨论(0)
  • 2020-12-31 21:47

    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;
    }
    
    0 讨论(0)
  • 2020-12-31 21:50

    The simplest, most dangerous way to accomplish this is to use a [% PERL %] block and force the evaluation to occur in the main namespace.

    [% PERL %]
    package main;
    # You can now use any variables and subroutines as though this were in the main namespace
    [% END %]
    

    This is necessary because the [% PERL %] block is evaluated in an isolated Template::Perl package namespace, which you are overriding with package main

    The danger comes from your template being able to write into the main namespace in addition to reading from it, which can lead to some interesting debug.

    0 讨论(0)
提交回复
热议问题