Synopsis
<#function name param1 param2 ... paramN>
...
<#return returnValue>
...
</#function>
Where:
-
name
: name of method variable (not expression) -
param1
,param2
, ...etc.: the name of the local variables store the parameter values (not expression), optionally followed by=
and the default value (that's an expression). -
paramN
, the last parameter, may optionally include a trailing ellipsis (...
), which indicates the macro takes a variable number of parameters. Local variableparamN
will be a sequence of the extra parameters. -
returnValue
: the expression that calculates the value of the method call.
The return
directive can be used anywhere
and for any times between the <#function
...>
and
</#function>
.
Parameters without default value must precede parameters with
default value
(paramName=defaultValue
).
Description
Creates a method variable (in the current namespace, if you
know namespace feature). This directive works in the same way as the
macro
directive, except that return
directive
must have a parameter that specifies the return
value of the method, and that attempts to write to the output will
be ignored. If the </#function>
is reached
(i.e. there was no return
returnValue
), then the return
value of the method is an undefined variable.
Example 1: Creating a method that calculates the average of two numbers:
<#function avg x y> <#return (x + y) / 2> </#function> ${avg(10, 20)}
will print:
15
Example 2: Creating a method that calculates the average of multiple numbers:
<#function avg nums...> <#local sum = 0> <#list nums as num> <#local sum += num> </#list> <#if nums?size != 0> <#return sum / nums?size> </#if> </#function> ${avg(10, 20)} ${avg(10, 20, 30, 40)} ${avg()!"N/A"}
will print:
15 25 N/A