Search code examples
perltemplate-toolkit

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?


Solution

  • 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/