freemarker

Recursive function changes variable value of caller function


This is a POC code on freemarker recursive function call. The actual code is a bit complex.

Here when I call the above template, the function recursively calls itself. I initialize the temp variable with init. The recursive function calls itself passing temp value . now the recursive call's temp should be local to that subroutine call however it affects the caller's temp variable's value. The final output here is 'temp' instead of 'init'.

Is this the usual behavior? how can i avoid the callers variable to not change during recursive call

${getTempVar('init')}

<#function getTempVar var >
    <#assign temp = var>
    <#if var == 'init' && getTempVar('temp') == 'temp'>
    </#if>
    <#return temp>
</#function>

Solution

  • Use <#local temp = ...> instead of <#assign temp = ...>, and it will work as expected. #assign sets in the namespace of the main template (almost a global variable). (#local I believe was added later, so the naming is not great.)