Dynamic Freemarker variable name

本小妞迷上赌 提交于 2019-12-02 03:39:39

问题


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?


回答1:


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.




回答2:


I had a similar problem and Special Variable Reference page helped me:

vars: Expression .vars.foo returns the same variable as expression foo. It's useful if for some reasons you have to use square bracket syntax, since that works only for hash sub variables, so you need an artificial parent hash. For example, to read a top-level variable that has a strange name that would confuse FreeMarker, you can write .vars["A strange name!"]. Or, to access a top-level variable with dynamic name given with variable varName you can write .vars[varName]. Note that the hash returned by .vars does not support ?keys and ?values.

In my case I had to use only strings in my model. I had a bunch of names like Name1, Name2, ... Name10. To make a table of these names I used this code:

<#list 1..10 as x>
<#if .vars["Name" + x]??>
 <tr>
 <td align="center">${.vars["Name" + x]}</td>
 </tr>
</#if>
</#list>



回答3:


Use a hash. That is, use the name of the variable as the key of the hash.




回答4:


I guess you can do it like this:

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

I found the answer from here, and it works to me.



来源:https://stackoverflow.com/questions/24086758/dynamic-freemarker-variable-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!