8.4 #set

Syntax:

#set [global] $var = EXPR

#set is used to create and update local variables at run time. The expression may be any Python expression. Remember to preface variable names with $ unless they're part of an intermediate result in a list comprehension.

Here are some examples:

#set $size = $length * 1096
#set $buffer = $size + 1096
#set $area = $length * $width
#set $namesList = ['Moe','Larry','Curly']
#set $prettyCountry = $country.replace(' ', ' ')

#set variables are useful to assign a short name to a $deeply.nested.value, to a calculation, or to a printable version of a value. The last example above converts any spaces in the 'country' value into HTML non-breakable-space entities, to ensure the entire value appears on one line in the browser.

#set variables are also useful in #if expressions, but remember that complex logical routines should be coded in Python, not in Cheetah!

#if $size > 1500
  #set $adj = 'large'
#else
  #set $adj = 'small'
#end if
Or Python's one-line equivalent, "A and B or C". Remember that in this case, B must be a true value (not None, '', 0, [] or ).
#set $adj = $size > 1500 and 'large' or 'small'
(Note: Cheetah's one-line #if will not work for this, since it produces output rather than setting a variable.

You can also use the augmented assignment operators:

## Increment $a by 5.
#set $a += 5

By default, #set variables are not visible in method calls or include files unless you use the global attribute: #set global $var = EXPRESSION. Global variables are visible in all methods, nested templates and included files. Use this feature with care to prevent surprises.