[Templates] Loops and scoping

[prev] [thread] [next] [Date index for 2004/10/25]

From: Jesse Sheidlower
Subject: [Templates] Loops and scoping
Date: 23:35 on 25 Oct 2004
It seems that every time I go back to this, I get bitten again,
so finally I'd like to see if there's a better way.

I frequently have loops more or less like the following:

[% FOREACH book = books %]
  [% SET biblio = book.biblio IF book.biblio %]
  [% biblio = biblio | some_filter %]

  ...
  [%# something that displays my book %]
[% END %]

Then, when I run into a record with no biblio, I get the
previous one repeated because the "biblio" var doesn't get
cleared at the end of the loop. So at the end of my loop, I
have to remember to undef all the variables I used
within. This is annoying, and contrary to what I expect in
Perl.

I assume, but am not sure, that this is what the Directives
chapter is referring to by "under normal operation, the loop
variable remains in scope after the FOREACH loop has ended".
If so, perhaps it could be made more clear. If I'm just missing
what's right in front of my eyes, I'd be grateful for a pointer.
Either way, is there a way of doing this that's more natural
than undef'ing each variable individually before the loop ends?

Thanks.

Jesse Sheidlower

P.S. I do note that there are times when I _do_ set a variable
_outside_ the loop that I then modify inside the loop--a variable
controlling the color of alternating rows, for example--and I 
don't want this to be reset. Basically if I declare a variable
inside the loop, I only want it scoped within that loop, like
normal in Perl.

_______________________________________________
templates mailing list
templates@xxxxxxxxxxxxxxxx.xxx
http://lists.template-toolkit.org/mailman/listinfo/templates

[Templates] Loops and scoping
Jesse Sheidlower 23:35 on 25 Oct 2004

Re: [Templates] Loops and scoping
Andy Wardley 08:01 on 26 Oct 2004

Re: [Templates] Loops and scoping
Jesse Sheidlower 14:18 on 26 Oct 2004

Generated at 08:55 on 15 Mar 2005 by mariachi v0.52