【问题标题】:How to define a default argument value in template toolkit MACRO如何在模板工具包 MACRO 中定义默认参数值
【发布时间】:2021-09-27 11:18:32
【问题描述】:

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

【问题讨论】:

  • 也许您可以使用宏块开头的PERL 指令来修改存储?如果未将 stash 变量作为参数给出,它将被设置为空字符串,因此您可以执行类似 my $arg3 = $stash->get('arg3'); $arg3 = 'my_default_value' if $arg3 eq ""; $stash->set(arg3 => $arg3) 的操作

标签: perl template-toolkit


【解决方案1】:

这是一个示例,说明如何在未提供宏参数的情况下使用 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,

【讨论】:

  • 这很有趣。如果您在输入宏时调用[% arg3.defined %],您将看到arg3 未定义。但是在 Perl 代码中,$stash-&gt;get('arg3') 返回一个定义的值。所以你无法区分无参数和空字符串。
  • 是的,调用[% my_macro("a","b","") %] 会为您提供默认值。
【解决方案2】:

毫无疑问,您建议的语法会引发语法错误。因为 TT 不支持。

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

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

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

【讨论】:

  • 对不起,我不明白这一行 Arg 3 is [% arg3 %] 你确定是正确的吗?
  • @eduardosufan:是的,没错。我不知道你的宏需要做什么,所以我只生成了最简单的调试输出。它显示字符串“Arg 3 is”,后跟arg3 的值。你不明白什么?
  • 哦,我没看到那是一个字符串。现在我明白了。谢谢。
猜你喜欢
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 2021-12-27
  • 2018-07-16
  • 2019-09-12
  • 2012-09-21
  • 1970-01-01
相关资源
最近更新 更多