Re: FOREACH question

Tom Molesworth <tom-UE50auxAeIt4LjgWlUEQQwC/[email protected]> Thu, 23 Aug 2012 14:23:49 +0100
Newsgroups gmane.comp.lang.perl.modules.template-toolkit
Message-ID <[email protected]>
On 23/08/12 13:15, Mark Haney wrote:
> I have a question regarding the FOREACH loops.  I have a FOREACH being 
> used to loop through an array to insert various images into a table. 
> Like this:
>
>>
>>         [% FOREACH light IN lights %]
>>             <td>
>>         <img src="[% light.light_red %]">
>>         <img src="[% light.light_yellow %]">
>>         <img src="[% light.light_green %]">
>>         <img src="[% light.light_blue %]">
>>             </td>
>>
>>         [% END %]
>
> What I need to do now is to loop through each element in the array 
> (like a counter) and insert the images into it's own table.  Like this:
>
> FOR a <= 3
>     <table>
>      <tr>
>          <td>
>      <img src="[% light.[$a] %]">
>          </td>
>      </tr>
>      </table>
> a= a++
> NEXT
>
> The problem is I don't know how to tell it the number of elements in 
> the array (in this instance it will always be 4).

Not sure why you need a count there, if you're going to iterate through 
all the elements anyway - seems this would do the trick:

[% FOREACH l IN light %]
...[% l %]
[% END %]

The .size vmethod would give you the total number of elements in the 
array, if that's what you're asking - 
http://template-toolkit.org/docs/manual/VMethods.html#section_size_max

If you do need the index then try using the loop iterator - 
http://template-toolkit.org/docs/manual/Directives.html#section_Loop_Processing 
has some examples:

[% FOREACH light IN lights %]
...
Item [% loop.index %]: [% light %]
[% END %]

cheers,

Tom

_______________________________________________
templates mailing list
[email protected]
http://mail.template-toolkit.org/mailman/listinfo/templates