One of the most common templating tasks is the need to produce output from a sequence of items. For instance, we may need to fill a table with values, or dynamically generate a list-box. Cubictemp provides a repeat construct to take care of this problem.
<!--(for foo in bar)-->
@!foo!@
<!--(end)-->
The template above does exactly what anyone familiar with Python would expect - it loops through all elements of "bar" (which has to be a sequence or an iterator), setting the value of "foo" to each element in turn. As in simple substitutions, the sequence definition is evaluated as an expression. This allows us to do things like the following:
<!--(for foo in range(3))-->
Counting: @!foo!@
<!--(end)-->
... producing the output:
Counting: 0
Counting: 1
Counting: 2
The following short example illustrates the use of repeat blocks. Say we need to dynamically generate a list box. First, we construct a general template for a simple select box:
<select>
<!--(for option in optionList)-->
<option>
@!option!@
</option>
<!--(end)-->
</select>
Notice that we have chosen our block flavour so that the HTML in the raw template is well-formed. This means that we can simply view the raw template in a web-browser while we edit, to check that the output is what we want:
OK, the template seems to be correct - the list box looks right, and our option replacement tag appears in the right place. Now we need to combine it with code to actually do the substitution:
import cubictemp
opts = ["Elephants", "Buffaloes", "Hippopotami", "Rhinoceri"]
temp = cubictemp.File("template", optionList = opts)
print temp
All of this combined, produces the lovely select box shown below:
<--previous | contents | next--> | (11/16/04) |