Search code examples
perltemplate-toolkit

How do statement modifiers work in Template Toolkit?


Consider these TT commands (run in order):

[% x = "foo" %]        # x == "foo" 
[% x = "bar" IF 1 %]   # x == "bar"
[% x = "bar" IF 0 %]   # x == ""

Why does x get assigned to an empty string in the 3rd statement?


Solution

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

    Note one important caveat of using this syntax in conjunction with side-effect notation. The following directive does not behave as might be expected:

    [% var = 'value' IF some_condition %]   # does not work
    

    In this case, the directive is interpreted as (spacing added for clarity)

    [% var = IF some_condition %]
       value
    [% END %]
    

    rather than

    [% IF some_condition %]
        [% var = 'value' %]
    [% END %]
    

    The variable is assigned the output of the IF block which returns 'value' if true, but nothing if false. In other words, the following directive will always cause 'var' to be cleared.

    [% var = 'value' IF 0 %]
    

    To achieve the expected behaviour, the directive should be written as:

    [% SET var = 'value' IF some_condition %]