Function in XML

Creates a method variable. This directive works in the same way as the macro directive, except that return the 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: TEMPLATE

<#function avg x y>
  <#return (x + y) / 2>
</#function>
${avg(10, 20)}

will print: OUTPUT

15

Example 2: Creating a method that calculates the average of multiple numbers: TEMPLATE

<#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: OUTPUT

15
25

Leave a comment

Your email address will not be published. Required fields are marked *