cjh
cjh

Reputation: 1133

Template toolkit FOR and IF behavior

I am experiencing weird behavior with template toolkit, say I have a data structure (defined in perl and passed as a parameter):

( { FLAG => 1, some => data}, { some => data}, etc )

and in a template I have a loop like

[FOR ITEMS]
  [IF (FLAG) ]
    do something
  [ELSE]
    do something else
  [END]
[END]

the template seems to never enter the else, the only way I can get it to enter the else is to change the data:

( { FLAG => 1, some => data}, { FLAG => 0, some => data}, etc )

so that it evaluates to false. However if I then change the data structure to

( { some => data}, { some => data}, etc )

It always enters the else (because it evaluates undef to be false).

It seems as if there is some 'bleed over' of variables remaining in scope for the next iteration unless they are overwritten, is this expected behavior? and if so is it documented anywhere?

EDIT: Later on I found it was a different issue causing the above behavior, it was due to me using "ELSEIF" and not the correct "ELSIF" elsewhere in the template. If in doubt check out the solution proposed by jira which solved the problem I described in my origional post.

Upvotes: 2

Views: 1049

Answers (1)

jira
jira

Reputation: 3944

You can modify the template like below assigning the loop variable to a named hash. Then it will behave as you expect.

[%FOREACH ITEM IN ITEMS%]

  [%IF ITEM.FLAG %]
    do something
  [%ELSE%]
    do something else
  [%END%]

[%END%]

Upvotes: 4

Related Questions