Scripting in Tapestry requires some extra thought; in the examples above, the web developer specifically knew the URLs of the images to preload and the name of the <img> element to be affected. For Tapestry, those things are not known ahead of time; scripting is a matter of plugging in variable content to a template.
Tapestry supports scripting with the Tapestry Script document, another XML document type. A Tapestry script takes as input a number of symbols and uses them to construct the desired JavaScript event handlers, and to provide initializations for them.
Script documents, which use the filename extension .script, consist of a <script> element.
Figure 12.2. Script document: <script> element
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE script PUBLIC "-//Howard Ship//Tapestry Script 1.1//EN" "http://tapestry.sf.net/dtd/Script_1_1.dtd"> <script> [ <include-script ... /> ... ] |
This element is used to include external, static, JavaScript scripts on the rendered page. This is useful to in cases where large parts of the JavaScript do not depend on any dynamic symbols. The path is to a resource on the class path, much like a private asset.
Figure 12.4. Script document: <let> element
<let key="symbol-name"> |
This element is used to define new symbols. The most common use of this is to define the name of a function, usually by combining some unique name or id with other text. This new symbol is then used in the <body> element to define the function, and in the <initialization> element to establish the function as the handler for some HTML element's event.
The <let> elements are evaluated in order. Often, some building block symbols are established first; other symbols add suffixes and prefixes to form the final names of functions.
The <insert> element is used to insert the value of a property. Simple names are just the names of symbols passed to the script, or the names can be a full property path (operating like a <binding> element in a component specification).
Figure 12.6. Script document: <if> element
<if property-path="property-path"> [ full content ] </if> |
The <if> element provides some conditional content. It evaluates its property and, if true (generally, non-null, non-empty or non-zero, depending on the type), it includes its content. The content is full content, meaning just about anything can be contained (including <if>, <foreach>, etc.).
Figure 12.7. Script document: <if-not> element
<if-not property-path="property-path"> [ full content ] </if> |
The <if-not> element is the same as the <if> element, but it inverts the meaning of the property, including its content if the property is false.
Figure 12.8. Script document: <foreach> element
<foreach key="key" property-path="property-path"> [ full content ] </foreach> |
The <foreach> element is an analog of the Foreach component; it iterates through a list of objects. On each iteration, it sets the named symbol (via the key attribute) and inserts its body.