Re: [Templates] Loops and scoping
[prev]
[thread]
[next]
[Date index for 2004/10/26]
Jesse Sheidlower wrote:
> 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.
[...]
> 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".
Not quite. This refers only to the 'loop' variable.
The issue is that TT2 does not have lexical (i.e. block-based) scoping of
variables. It's the Perlish equivalent of this:
my $biblio;
for (...) {
$biblio = $value;
}
Rather than this:
for (...) {
my $biblio = $value;
}
Although it's worth noting that TT2 doesn't actually do either because it
uses the stash to store variables rather than using 'my'. But hopefully it
illustrates the point that any variables (except 'loop') are scoped within
the template as a whole, rather than be local to a FOREACH loop.
So in this case, you do need to specifically unset the biblio variable if
you're relying on that behaviour.
e.g.
[% IF book.biblio;
bibio = book.biblio | some_filter;
ELSE;
biblio = '';
END
%]
Or maybe just something like the following, where you'll get the filtered
biblio or an empty string:
[% biblio = book.biblio | some_filter # may be empty %]
> Basically if I declare a variable
> inside the loop, I only want it scoped within that loop, like
> normal in Perl.
This is one of the things that I'm currently addressing in the design of
TT3. I'm planning for the MY keyword (or something similar) to be used
to declare variables that are truly local, and would be implemented in
the underlying Perl code by 'my' variables rather than the stash.
# tt3_my_example: example of MY keyword in TT3
[% x = 10 %] # regular TT variable stored in stash
[% MY y = 20 %] # truly local variable, implemented using 'my' in Perl
[% FOREACH picture IN album %]
[% MY x = 15, y = 25 %] # block local variables
[% x %] # 15
[% y %] # 25
[% END %]
[% x %] # 10
[% y %] # 20
As well as being faster to access, MY variable also have the benefit of
remaining truly local to the template. If you PROCESS the above template,
you'll end up with x set to 10, as per TT2, but any y variable will remain
unaffected.
[% x = 1, y = 2 %]
[% PROCESS tt3_my_example %]
[% x %] # 10
[% y %] # 2
Cheers
A
_______________________________________________
templates mailing list
templates@xxxxxxxxxxxxxxxx.xxx
http://lists.template-toolkit.org/mailman/listinfo/templates
 |
 |
Re: [Templates] Loops and scoping
Andy Wardley 08:01 on 26 Oct 2004
|