Now that you've got the skinny on variables and conditional statements, expand your knowledge of the ZPT universe with this discussion of TAL loops, dynamically-generated attributes and error handlers.
Not impressed yet? Let's alter the code a little to see what else you can do with sequences.
<span tal:repeat="fruits python:'apple', 'banana', 'orange', 'apricot',
'grape'">
<i tal:condition="repeat/fruits/start">Here's where it all
starts</i> <br>
I am a <span tal:replace="fruits" />, my sequence
position is <span tal:replace="repeat/fruits/number"
/>,
and my index number is <span tal:replace="repeat/fruits/index" />. <br>
<i
tal:condition="repeat/fruits/end">And here's where it all ends.</i>
</span>
Now take a look at the output.
Here's where it all starts
I am a apple, my sequence position is 1, and my index
number is 0.
I am a banana, my sequence position is 2, and my index number is
1.
I am a orange, my sequence position is 3, and my index number is 2.
I am
a apricot, my sequence position is 4, and my index number is 3.
I am a grape,
my sequence position is 5, and my index number is 4.
And here's where it all
ends.
How does this work? Well, you may remember, from your DTML exploits, that all
sequences have built-in variables that can be used to identify the current pointer position within the sequence. The "number" variable represents the position of the current item in the sequence, while the "index" variable provides an alternative zero-based indexing mechanism that serves the same purpose. And the "start" and "end" variables provide an easy way to find out if you're at the beginning or end of the sequence - the former is true when the current item is the first element of the sequence and the latter is true when the current element is the last element of the sequence.
Now, in order to access these values in your Zope Page Templates, you need to use one or more TALES expressions. Here are the ones I've used:
repeat/fruits/start - A TALES expression for the value of the "start" variable
repeat/fruits/number - A TALES expression for the value of the "number" variable
repeat/fruits/index - A TALES expression for the value of the "index" variable
repeat/fruits/end - A TALES expression for the value of the "end" variable
You may remember, from earlier articles in this series, that every TALES path must begin with a variable name. "repeat" is one such pre-defined variable, and it stores information on the start and end position, number, index and length of the sequence. This information can then be accessed using a three-part path, such as the ones demonstrated above
The example you just saw used a simple sequence. However, you can also loop over a collection of objects using the same technique. Take a look at a simple example that lists the objects in the current folder.
Here, I've used the "container" built-in variable together with the "objectIds"
variable, which returns a sequence with the list of objects in the current folder.