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.
ZPT also allows you to dynamically generate attributes and attribute values in a template, via the special "attributes" attribute (try saying that fast!). This TAL attribute makes it possible to dynamically assign values to HTML attributes, or to replace default attribute values with user-supplied ones.
In order to illustrate, consider the following simple template (named "SticksAndStones"):
<font tal:attributes="size request/size;color request/color; face
request/face">
Sticks and stones will break my bones </font>
In this case, the font face, colour and size will be dynamically set by ZPT based
on values in the URL request. So, when you access this particular page with the following URL,
If you take a look at the source code of the dynamically-generated page, you'll see that ZPT has used the values passed on the URL within the template, via the special "attributes" attribute, to dynamically generate HTML attributes for the <font> tag.
You can also specify default values for your HTML attributes, and have ZPT replace them with user-defined ones if available. In order to illustrate this, consider the following rewrite of the previous example:
<font color="blue" size="2" face="verdana"
tal:attributes="color request/color
| default; size request/size |
default; face request/face | default"> Sticks and
stones will break my
bones </font>
In this case, if I access the URL
http://localhost:8080/SticksAndStones
without sending it any input parameters, the template will use the default attributes
of the <font> tag,
it will replace the default attribute values with the user-supplied values.
Note my usage of the | conditional operator and the special "default" keyword, which tells ZPT to use the default value in case a user-supplied value is not available.
Here's another example, this one demonstrating how the "attributes" attribute may be used in combination with a loop:
<span tal:repeat="s python:1,2,3,4,5">
<font face="Verdana" tal:attributes="size
s">
Sticks and stones will break my bones
</font>
<br>
</span>
In this case, the "repeat" attribute is used to iterate through a sequence of
font sizes, with the "attributes" attribute used in each iteration to dynamically generate a new "size" attribute for the <font> tag. Here's the output: