Last time out, DTML Basics demonstrated conditional statements. This time around, it's time to study loops...which, in the DTML world, aren't exactly what you're used to. Take a look.
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 (use a DTML Method here instead of a DTML Document).
This folder contains:
<ul><dtml-in expr="objectIds()">
<li><dtml-var
sequence-item></li>
</dtml-in>
</ul>
Over here, I've used the ObjectIds() method of the ObjectManager class to produce
a list of objects, and iterated through that list using a DTML loop. For the uninitiated, the ObjectManager class is a class that contains other Zope objects; it provides methods that allow you to find out about the objects it "manages".
Let's replace ObjectIds() with ObjectValues(), in order to make things a little more interesting.
<dtml-in expr="objectValues()">
<dtml-if sequence-start><b>There are
<dtml-var sequence-length> items
in this folder.</b><br></dtml-if>
This is <dtml-var sequence-var-id>.
<br> <dtml-var sequence-item><p>
</dtml-in>
Check the output and get ready for a big surprise.
How did this happen? Well, the ObjectValues() method returns the objects present in the folder. So, when I reference each item with the "sequence-item" variable, I'm actually accessing the object itself, and displaying the output of the DTML code that is present in the object.
Once again, the "sequence-length" variable has been used to display the number of objects in the current folder. But how was I able to display the ID of the object at the beginning of each listing?
This is another feature available with sequences: you can access all the variables associated with an object using the following syntax:
sequence-var-varname
where varname is the name of the variable whose value you want to display. So,
you can access the title using "sequence-var-title" or the object ID using "sequence-var-id", just as in the example above.
And here's another variant of the example above:
<dtml-in expr="objectItems()">
This is <dtml-var sequence-key>
<br>
<dtml-var
sequence-item>
<p>
</dtml-in>
The output is the same as that of the previous example. However, over here, I've
used the ObjectItems() method of the Object Manager. This returns the objects in the form of a tuple (a container variable, which can contain one or more values, kinda like an associative array or hash). The ObjectItems() method returns the IDs and the objects as key-value pairs, so you can access the name of the object by using the "sequence-key" variable and the object itself using the "sequence-item" variable.