首页 > 解决方案 > 如何在模板工具包 MACRO 中定义默认参数值

问题描述

我想用几个参数定义一个模板工具包宏,如果在那个位置没有给出参数,至少有一个具有默认值。可能吗?我的想法是有这样的东西(类似于 Python 语法/逻辑):

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

标签: perltemplate-toolkit

解决方案


正如您毫无疑问地发现的那样,您建议的语法会引发语法错误。因为TT不支持。

您可以采用Håkon 采用的方法,但如果您想要一些更简单的东西,不需要[% PERL %]块,您可以执行以下操作:

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

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

推荐阅读