Setting element attributes

The TAL attributes attribute controls the adding, removal or setting of attributes upon the rendered element.

Syntax

tal:attributes="ATTRIBUTE_NAME EXPRESSION"

The attribute name

The attribute name (ATTRIBUTE_NAME) is mandatory and specifies the name of the attribute to modify. It may optionally contain a namespace prefix in the PREFIX:NAME syntax. This is useful for XML documents which include attributes from multiple namespaces.

The expression

The expression (EXPRESSION) is evaluated as a TALES expression; and the result depends upon the value of that expression, using the following logic:

  1. If the expression evaluates to null then the named attribute is not added to the element; if it is already present then it is removed.
  2. If the expression cancels the action then the attribute is not added to the element. If it is already present then it is left unchanged.
  3. If the expression evaluates to any other value then the named attribute is either added to the element or, if it is already present its value is modified. The attribute's new value is the result of expression.

In the last case, where an attribute value is added or modified, the expression result is interpreted as a System.String, if it is not already a string then it is converted using the object's ToString() method. The expression result is escaped (HTML encoded) before it is rendered as an attribute value.

Setting multiple attributes at once

It is permitted to include multiple attributes statements in the same tal:attributes attribute. Each statement is separated by a semicolon (and optional whitespace for readability):

<input tal:attributes="class string:my_class my_other_class;
                       type Model/My/Value;
                       readonly string:readonly" />

If you wish to use a semicolon character in an attribute name or expression (for example as part of a string: TALES expression) then you must escape it by doubling-it up: ;;.

If multiple attribute statements are present upon the same attribute in this manner, they are evaluated independently with regard to handling of null values and cancellation of the action. Thus attributes may be added and removed via the same tal:attributes attribute.