语句修饰符如何在Template Toolkit中起作用?

Eug*_*ash 1 perl template-toolkit

考虑这些TT命令(按顺序运行):

[% x = "foo" %]        # x == "foo" 
[% x = "bar" IF 1 %]   # x == "bar"
[% x = "bar" IF 0 %]   # x == ""
Run Code Online (Sandbox Code Playgroud)

为什么x在第3个语句中将其分配给空字符串?

Nyl*_*ile 8

http://template-toolkit.org/docs/manual/Syntax.html#section_Capturing_Block_Output

请注意将此语法与副作用符号结合使用时的一个重要警告.以下指令的行为与预期不符:

[% var = 'value' IF some_condition %]   # does not work
Run Code Online (Sandbox Code Playgroud)

在这种情况下,指令被解释为(为了清晰起见而添加间距)

[% var = IF some_condition %]
   value
[% END %]
Run Code Online (Sandbox Code Playgroud)

而不是

[% IF some_condition %]
    [% var = 'value' %]
[% END %]
Run Code Online (Sandbox Code Playgroud)

变量被赋予IF块的输出,如果为真,则返回'value',但如果为false,则返回任何内容.换句话说,以下指令将始终导致'var'被清除.

[% var = 'value' IF 0 %]
Run Code Online (Sandbox Code Playgroud)

为了达到预期的行为,该指令应写为:

[% SET var = 'value' IF some_condition %]
Run Code Online (Sandbox Code Playgroud)