开发者

How can you pass undef as an argument to an object method from a TT template?

开发者 https://www.devze.com 2022-12-10 22:28 出处:网络
Template-Toolkit seems to want to always interpolate undef to the empty string. So a template like this:

Template-Toolkit seems to want to always interpolate undef to the empty string. So a template like this:

Result is [% some_object.some_method (1开发者_如何学JAVA, undef, 2) %]

or this:

Result is [% ttvar %]
          [% some_object.some_method (1, ttvar, 2) %]

produces a call to Perl like:

some_object->some_method (1, '', 2)

when what I want is:

some_object->some_method (1, undef, 2)

Is there any way to pass undef instead of an empty string?


I've added another answer to show an example of how EVAL_PERL works in TT:

use Template;
use DateTime;

my $tt = Template->new( EVAL_PERL => 1 );

my $vars = { foo => 'DateTime', bar => DateTime->now, p => 'print' };

my $file = q{
    [% SET hello = 'Hello world' %]
    [% PERL %]
    print "[% hello %]\n";
    print [% foo %]->now, "\n";
    [% p %] $stash->get( 'bar' )->ymd;
    [% END %]
};

$tt->process( \$file, $vars );

The above outputs the following:

Hello world
2009-11-03T15:31:50
2009-11-03

Because TT is acting as a pre-processor and produces the following Perl code to interpret:

print "hello world\n";
print DateTime->now, "\n";
print $stash->get( 'bar' )->ymd;

NB. $stash in above line is provided by TT and is a reference to the top level stash object.

/I3az/


How about using [% PERL %]?

[% PERL %]
[% my_perl_code %]
[% END %]


This is a design decision with Template Toolkit. From page 50 of the Perl Template Toolkit "Badger book":

The Template Toolkit won't complain if it encounters a variable for which it doesn't have a value defined. Instead, it will quietly use an empty string (i.e., nothing at all) for the value of the variable and continue to process the reminder of the template.

However what you can do is make TT provide a warning when it sees an undef by using the DEBUG option. See the SO question Can Perl’s Template Toolkit warn on undefined values? for more info.

/I3az/

0

精彩评论

暂无评论...
验证码 换一张
取 消