[Templates] Using FOREACH i IN [0 .. max]

Buddy Burden buddy@thinkgeek.com
Fri, 27 Apr 2007 18:30:24 -0400


Mark,

 > I couldn't find a "for" inside TT, but I saw that I could write something
 > like:
 >
 > [% FOREACH i IN [0 .. LISTSIZE] %]
 > ... Doing stuff with [% i %]
 > [% END %]

Well, this should work (untested):

	[% FOREACH i IN [0..LISTSIZE] %]
		[% UNLESS loop.last %]
			[%# do something with i %]
		[% END %]
	[% END %]

But my real question to you would be this:

> In Perl, I would write
> something like this:
> 
> for ($i=0; $i < $LISTSIZE; $i++) {
> # Doing stuff with $i
> }

Why?  I hardly ever write for loops like that (the only time I can think of is for iterating two arrays in parallel, and 
Perl 6 will fix that for me).  I almost always write:

	foreach my $item (@LIST)
	{
		# doing stuff with $item
	}

If you're able to do something like that, it would eliminate the problem altogether.  Of course in Perl if you need $i 
for anything other than indexing the array, you're sort of hosed, but in TT2, you can always use [% loop.index %] (or [% 
loop.count %]) instead.


		-- Buddy