4.2 HTML Attribute Substitution

In the last section, you saw how arbitrary Python could be embedded in HTML using processing instructions. Since the HTML template must be syntactically valid HTML, this presents a problem when you only want to manipulate a single attribute of an HTML tag. You can do this using attribute substitution, which looks very similar to the processing instruction syntax.

The most common method of attribute substitution is replacing the value of an HTML attribute with the value of a Python expression. This can be accomplished by making the first character of the attribute the equals symbol ("=") as follows:

<body bgcolor="=color">

where the variable color has been previously defined in Python code. This is nearly identical to the behavior of processing instructions that begin with "=", except that the value is substituted for the tag's attribute.

There are cases where attributes do not take values, and are only present to indicate a certain condition. Examples of such attributes include <COMPACT>, <DISABLED>, <NOWRAP> and <SELECTED>. To conditionally include one of these attributes in a tag, begin the attribute value with a question mark ("?") as follows:

<option value="spam" selected="? selected_option == 'spam'">Spam</option>

Whatever follows the question mark must be a valid Python expression that evaluates to either True or False.

Note: In versions previous to 2.0, the question mark indicated that the value was to be evaluated as a Python statement. This behaviour was dubious as to its practical uses and is no longer supported by PSE.