If you use Cheetah, please support the project and register by clicking here:


9.1 #for ... #end for

Syntax:

#for $var in EXPR
#end for

The #for directive iterates through a sequence. The syntax is the same as Python, but remember the $ before variables.

Here's a simple client listing:

<TABLE>
#for $client in $service.clients
<TR>
<TD>$client.surname, $client.firstname</TD>
<TD><A HREF="mailto:$client.email" >$client.email</A></TD>
</TR>
#end for
</TABLE>

Here's how to loop through the keys and values of a dictionary:

<PRE>
#for $key, $value in $dict.items()
$key: $value
#end for
</PRE>

Here's how to create list of numbers separated by hyphens. This ``#end for'' tag shares the last line to avoid introducing a newline character after each hyphen.

#for $i in range(15)
$i - #end for

If the location of the #end for offends your sense of indentational propriety, you can do this instead:

#for $i in $range(15)
$i - #slurp
#end for

The previous two examples will put an extra hyphen after last number. Here's how to get around that problem, using the #set directive, which will be dealt with in more detail below.

#set $sep = '' 
#for $name in $names 
$sep$name 
#set $sep = ', ' 
#end for

Although to just put a separator between strings, you don't need a for loop:

#echo ', '.join($names)

If you use Cheetah, please support the project and register by clicking here: