perl - 如何在模板工具包 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');
解决方案
正如您毫无疑问地发现的那样,您建议的语法会引发语法错误。因为TT不支持。
您可以采用Håkon 采用的方法,但如果您想要一些更简单的东西,不需要[% PERL %]
块,您可以执行以下操作:
[% MACRO my_macro( arg1, arg2, arg3) BLOCK;
arg3 = 'my default value' IF NOT arg3.defined -%]
Arg 3 is [% arg3 %]
[% END -%]
推荐阅读
- c# - C# 多态性和模板
- django - 为什么 Django 不在 for 循环中读取 HTML 代码?
- python - 使用 python 发送 Outlook 电子邮件
- vue.js - Vuejs 动态 div 文本
- r - 在 R 中重新编码未产生所需的输出
- powershell - 有没有办法创建自定义 Cloud Foundry Buildpack 来运行 Powershell 脚本?
- sql - SQL中按顺序排列的最大每组
- api - Blazor - WASM:加载资源失败:服务器响应状态为 404(未找到)
- r - 根据R中的组编号提取列的数据
- c++ - 如何在 C++ 中删除指向数组的指针