How to define a default argument value in template toolkit MACRO

222 Views Asked by At

I want to define a Template Toolkit MACRO with few arguments, and have at least one of them with a default value if no argument is given in that position. Is it possible? My idea is to have something like this (similar to Python syntax/logic):

[%- 
    MACRO my_macro( arg1, arg2, arg3='my_default_value') BLOCK;
        # arg3 value is 'my_default_value' if nothing is passed as argument in that position, otherwise it must use arg3 value given when called.
    END;
-%]

And then to call the macro:

# In this case, arg3 inside the macro must be 'my_default_value'
my_macro('my_value1', 'my_value2');

# In this case, arg3 inside the macro must be 'my_value3'
my_macro('my_value1', 'my_value2', 'my_value3');
2

There are 2 best solutions below

3
Dave Cross On BEST ANSWER

As you've no doubt found, your suggested syntax throws a syntax error. Because TT doesn't support that.

You can take the approach that Håkon takes, but if you want something a little simpler, that doesn't require a [% PERL %] block, you can do something like this:

[% MACRO my_macro( arg1, arg2, arg3) BLOCK;
     arg3 = 'my default value' IF NOT arg3.defined -%]

Arg 3 is [% arg3 %]
[% END -%]
2
Håkon Hægland On

Here is an example of how you can modify the stash using a PERL directive if a macro argument was not provided. This can by used to implement default values for the arguments to the macro:

use strict;
use warnings;
use Template;

my $template = Template->new({ EVAL_PERL => 1});
my $vars = { };
my $input = <<'END';
[%- MACRO my_macro(arg1, arg2, arg3) BLOCK -%]
  [% PERL %]
     my $arg3 = $stash->get('arg3');
     $arg3 = "my_default_value" if $arg3 eq "";
     $stash->set(arg3 => $arg3)
  [% END %]
  This is arg1 : [% arg1 %]
  This is arg2 : [% arg2 %]
  This is arg3 : [% arg3 -%]
[%- END -%]

Case 1: [% my_macro(1, 2, 3) %],
Case 2: [% my_macro("a","b") %],

END

$template->process(\$input, $vars) || die $template->error();

Output:

Case 1:   
  This is arg1 : 1
  This is arg2 : 2
  This is arg3 : 3,
Case 2:   
  This is arg1 : a
  This is arg2 : b
  This is arg3 : my_default_value,