perltemplate-toolkit

How to define a default argument value in template toolkit MACRO


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');

Solution

  • 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 -%]