这个问题是关于 Template::Toolkit (Perl) 中宏的使用
我无法编写宏并将它们放入单独的文件中以在其他几个模板文件中使用它们。
我的宏位于名为 macros.tt 的单独模板文件中:
----- file macros.tt ------
[% MACRO decorateStatus(status) BLOCK -%]
[% ico = 'status_unknown' -%]
[% IF status == "New" -%][% ico = 'status_waiting' -%]
[% ELSIF status == "Working" -%][% ico = 'status_work' -%]
[% ELSIF status == "Deleted" -%][% ico = 'status_deleted' -%]
[% END -%]
[% status %] <img src="[% c.uri_for('/images/ico/' _ ico _ '.png') %]" text="[% status %]">
[% END-%]
现在我正在尝试在另一个模板中使用这个宏——但是这失败了,因为宏没有展开:
----- file demo.tt -------
[% INCLUDE macros.tt %]
….
[% status = ‘New’ %]
<td>[% decorateStatus(status) %]</td>
….
将宏直接放在我想使用它的文件中,一切都按预期工作。
包含来自不同文件的宏的“正确”方法是什么?
最佳答案
使用 INCLUDE
,所有变量定义(宏实际上只是一个奇特的变量)都本地化到包含的文件中。这意味着宏定义在包含的文件之外不可见。
要使宏在调用文件中可见,您需要 PROCESS
而不是 INCLUDE
.如 the documentation says :
The
PROCESS
directive is similar toINCLUDE
but does not perform any localisation of variables before processing the template. Any changes made to variables within the included template will be visible in the including template.
关于perl - 如何包含 Template::Toolkit- Macros?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41718657/