Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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, 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?

like image 529
F5. Avatar asked Nov 25 '25 08:11

F5.


2 Answers

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/

like image 64
draegtun Avatar answered Nov 26 '25 23:11

draegtun


How about using [% PERL %]?

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!