<--previous | contents | next-->

Conditionals

Have a look at the example at the end of the previous section. We generated a select box, by passing a list of options to a specially crafted template that looked like this:

        <select>
        <!--(for option in optionList)-->
            <option>
                @!option!@
            </option>
        <!--(end)-->
        </select>

What happens if we need to pre-select one of our options? This would involve inserting our normal options as above, but making quite a different replacement for the pre-selected option. This requires a conditional - i.e. something like the if statement in Python. While Cubictemp discourages embedding program flow in templates, it does provide a built in conditional construct for cases like this. The conditional syntax is as explicit as possible: if conditional then a else b. Users familiar with C will recognise this construct as a more verbose version of the C ternary operator - (cond ? a : b). Like the C ternary operator, the Cubictemp if cond then a else b construct short-circuits i.e. if cond is positive, b will never get evaluated, and vice versa.

Before constructing the template for a select box with a pre-selected option, let's modify the Python code snippet from the previous example to encode the selection status of an option in our data.

import cubictemp opts = [("Elephants", 0), ("Buffaloes", 0), ("Hippopotami", 1), ("Rhinoceri", 0)] temp = cubictemp.File("template", optionList=opts) print temp

Each option now consists of a tuple - the first element is the text value, and the second element is the selection status. Our template can now be changed as follows:

        <select>
        <!--(for option in optionList)-->
                <option @!if (option[1]) then "selected" else ""!@>
                @!option[0]!@
                </option>
        <!--(end)-->
        </select>


This template inserts the word "selected" in the appropriate spot, if and only if option[1] is true. Either way, option[0] is inserted in the correct spot. The output from the code snippet and template looks like this:

Note that the "Hippopotami" option is now pre-selected.


<--previous | contents | next--> (11/16/04)
Cubictemp v0.4 Manual