如何在模板工具包 MACRO 中定义默认参数值

How to define a default argument value in template toolkit MACRO

我想定义一个带有少量参数的模板工具包 MACRO,并且如果在该位置没有给出参数,则至少有一个具有默认值。可能吗? 我的想法是有这样的东西(类似于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;
-%]

然后调用宏:

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

这是一个示例,说明如果未提供宏参数,您可以如何使用 PERL 指令修改存储。这可以用于实现宏参数的默认值:

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

输出:

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,

您肯定会发现,您建议的语法会引发语法错误。因为TT不支持。

你可以采用 的方法,但如果你想要更简单的东西,不需要 [% PERL %] 块,你可以这样做:

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

Arg 3 is [% arg3 %]
[% END -%]