Forum Discussion

PerBonomi's avatar
11 years ago

Loop through Freemarker variables?

I'm trying to loop through a list of Freemarker variables in javascript, but not having any luck. Is it possible?

 

Example. This works fine:

<#assign variable0 = "value0"/>
<#assign variable1 = "value1"/>
<#assign variable2 = "value2"/>

<script>
var arTest = new Array();
arTest[0] = '${variable0}';
arTest[1] = '${variable1}';
arTest[2] = '${variable2}';
</script>

 

But if I have a list of about 20+ variables, I'd really rather loop through. That, however, gives me a nasty error.

 

<#assign variable0 = "value0"/>
<#assign variable1 = "value1"/>
<#assign variable2 = "value2"/>

<script>
var arTest = new Array();
for (i=0; i < 3; i++) {
	arTest[i] = '${variable' + i + '}';
}
</script>

 

Freemarker template 'preview' parsing failed:
ParseException:Parsing error in template "preview" in line 36, column 31:
Encountered "\' + \'", but was expecting one of:
    "}"
    "."
    "["
    "("
    "?"
    "!"
    <TERMINATING_EXCLAM>
    "??"
    "+"
    "-"
    "*"
    "/"
    "%"
    "!="
    "="
    "=="
    ">="
    <ESCAPED_GTE>
    ">"
    <ESCAPED_GT>
    <LESS_THAN_EQUALS>
    <LESS_THAN>
    ".."
    <AND>
    <OR>

Also, if I escape the variable the result is ${variable0} instead of value0.

1 Reply

  • NicoB's avatar
    NicoB
    Lithium Alumni (Retired)
    11 years ago

    Hi PerBonomi 

    What you're trying to do is impossible because Javascript is running when the page has already been rendered by Freemarker.

    I would change your implementation with something similar:

     

    <script>
    <#assign bound = 3 />
    
    var arr = new Array(${bound}); //3 here must match the higher bound below.
    
    <#list 1..bound as curr>
      arr[${curr}] = ${("variable" + curr)?eval}
    </#list>
    </script>

     So, basically.. given bound the max number used for variableX (still wondering why you're not using a sequence anyway) I'm setting an element in the array using the Freemarker eval function which evaluate a string as Freemarker code (see here http://freemarker.org/docs/ref_builtins_expert.html#ref_builtin_eval)

    I'm not sure this code works because I haven't tested it but this could trigger some idea maybe?

    Edited: Reading the above Freemarker guide page I found that there's the interpret function which could also be helpful. 

    Thanks

    Nico