If you use Cheetah, please support the project and register by clicking here:


8.7 #def

Syntax:

#def METHOD[(ARGUMENTS)]
#end def

Or the one-line variation:

#def METHOD[(ARGUMENTS)] : TEXT_AND_PLACEHOLDERS

The #def directive is used to define new methods in the generated Python class, or to override superclass methods. It is analogous to Python's def statement. The directive is silent, meaning it does not itself produce any output. However, the content of the method will be inserted into the output (and the directives executed) whenever the method is later called by a $placeholder.

#def myMeth()
This is the text in my method 
$a $b $c(123)  ## these placeholder names have been defined elsewhere
#end def

## and now use it...
$myMeth()

The arglist and parentheses can be omitted:

#def myMeth
This is the text in my method 
$a $b $c(123)
#end def

## and now use it...
$myMeth

Methods can have arguments and have defaults for those arguments, just like in Python. Remember the $ before variable names:

#def myMeth($a, $b=1234)
This is the text in my method 
$a - $b
#end def

## and now use it...
$myMeth(1)

The output from this last example will be:

This is the text in my method 
1 - 1234

There is also a single line version of the #def directive. Unlike the multi-line directives, it uses a colon (:) to delimit the method signature and body:

#attr $adj = 'trivial'
#def myMeth: This is the $adj method 
$myMeth
Leading and trailing whitespace is stripped from the method. This is in contrast to:
#def myMeth2
This is the $adj method
#end def
where the method includes a newline after "method". If you don't want the newline, add #slurp:
#def myMeth3
This is the $adj method#slurp
#end def

Because #def is handled at compile time, it can appear above or below the placeholders that call it. And if a superclass placeholder calls a method that's overridden in a subclass, it's the subclass method that will be called.

If you use Cheetah, please support the project and register by clicking here: