<--previous | contents | next-->

Substitutions

Introduction to Substitutions

From the examples in the previous section, it may seem that text between the @!...!@ delimiters is treated simply as an identifier to be replaced. This is not the case - Cubictemp actually evaluates everything between the delimiters as an expression in the namespace specified by the keyword arguments. It is the result of this evaluation that is converted to a string with the built-in function repr, and placed in the template. This means that any valid Python expression which can be evaluated in the indicated namespace can appear in a substitution tag.

To illustrate this, take a look at the template below:

@!foo!@ times two is @!foo*2!@
@!foo!@ squared is @!foo*foo!@

...and this accompanying code snippet:

import cubictemp temp = cubictemp.File("template", foo=3) print temp

The output here would look like this:

3 times two is 6
3 squared is 9

Similarly, if "foo" happened to be a dictionary, we could extract a value from it inside a template like this:

@!foo["bar"]!@

And if "foo" was an object with an attribute "x", we could reference the attribute by saying:

@!foo.x!@

This ability to evaluate expressions makes Cubictemp templates very powerful and expressive.

A word about expressions and statements

At this point it is important to distinguish between Python expressions and Python statements. Python expressions can conveniently be thought of as anything that can be on the right-hand-side of an equals sign. Arithmetic operators, boolen operators, parentheses for grouping, method/function calls and object instantiation are all valid components of expressions. Python statements, on the other hand, include things like "if", "while", "print" and variable assignment. CubicTemp allows only expressions in places where it evaluates Python code. This is a deliberate choice - limiting templates to expressions ensures that all program logic lives in the Python program files where they belong. This enforces a hard separation between code and presentation, making it easier to unit-test, change and maintain the application as a whole.


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