问题
I am trying to create a FreeMarker macro that can return the interpolation of a concatenation of a string and the input variable:
<#macro findValue var>
<#if (.vars["foo." + var]) ??>
.vars["foo." + var]
<#else>
${.vars["bar." + var]}
</#if>
</#macro>
Unfortunately it doesn't work. Firstly, ${.vars["bar." + var]} gives an undefined error. Secondly, the if condition always returns false even when I can see that the sub variable do exist. It seems like the .vars variable can only look up root variables, but not sub variables like foo.test.
回答1:
In FreeMarker, foo.bar is the same as foo["bar"], but inside the [] you can have an arbitrary expression that evaluates to a string. So the expression you are looking for is simply foo[var].
BTW, what your macro tries to do is just ${foo[var]!bar[var]}
来源:https://stackoverflow.com/questions/12392822/freemarker-dynamic-interpolation-of-sub-variables