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.

Answers


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%]

Need Your Help

MYSQL : Undeclared variable

mysql stored-procedures

I have two stored procedure the first parameter with static and it works well

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.