Hi,

I have a sort of newbie question on using FOREACH with a range. I have a
collection of variables passed to Template Toolkit, and it'd be nice if I
can use LISTSIZE-1 kind of thing with FOREACH. In Perl, I would write
something like this:

for ($i=0; $i < $LISTSIZE; $i++) {
# Doing stuff with $i
}

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

This almost does what I want, but it includes LISTSIZE. I just need 0 to
LISTSIZE-1. So I've tried the following:

[% FOREACH i IN [0 .. LISTSIZE-1] %]
[% FOREACH i IN [0 .. LISTSIZE - 1 ] %]
[% FOREACH i IN [0 .. (LISTSIZE-1) ] %]
[% FOREACH i IN [0 .. (LISTSIZE - 1) ] %]
[% FOREACH i IN [0 .. "$LISTSIZE"-1 ] %]

But TT either doesn't like the minus sign or the open parens. I know I
can write something like:

[% SET max = LISTSIZE - 1; FOREACH i IN [0 .. max] %]
... Doing stuff with [% i %]
[% END %]

Or:

[% FOREACH j IN [1 .. LISTSIZE] %]
[% SET i = j - 1 %]
... Doing stuff with [% i %]
[% END %]

But that seems more error-prone. It'd be nice to be able to use
LISTSIZE-1 inside the range-specifier, but I'm having no luck figuring
out the "trick".

Any help would be appreciated. I'm using Template Toolkit 2.14. Oh, I
also tried out the syntax in Perl:

perl -e '$max=10; foreach $i (0 .. $max-1){ print "$i\n" }'

And it prints from 0 up to 9, so it doesn't look like Perl inherently has
this limitation.

Thanks
Mark

Reply via email to