function, return

Page Contents

Synopsis

<#function name param1 param2 ... paramN>
  ...
  <#return returnValue>
  ...
</#function>

Where:

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 = 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  
FreeMarker Manual -- For FreeMarker 2.3.20
HTML generated: 2013-06-27 20:54:33 GMT
Edited with XMLMind XML Editor
Here!