Search code examples
variablesfreemarker

Dynamic Freemarker variable name


I'm trying to set a variable with a dynamic name. This means the name for my new variable comes from another variable:

<#-- in real world I wouldn't declare this variables right here -
     they would come from somewhere else -->
<#assign varName = "myVarName"/>
<#assign varValue = "myVarValue/>

<#... set the variable .../>

So that the value can be referenced as follows:

${myVarName} <#-- prints "myVarValue" -->

In a Java directive I would use

Environment#setVariable(String name, TemplateModel model)

to achieve this. But is there a possibility to achieve this with Freemarker directly?


Solution

  • There's no directive that assigns to a variable that has a dynamic name. But here's a hack to achieve that:

    <@'<#assign ${varName} = varValue>'?interpret />
    

    This isn't terribly fast though. It involves FTL parsing each time it's evaluated.