Freemarker:子变量的动态插值

Freemarker:子变量的动态插值

问题描述:

我正在尝试创建一个FreeMarker宏,该宏可以返回字符串和输入变量的串联的插值:

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>

不幸的是,它不起作用.首先,${.vars["bar." + var]}给出undefined错误.其次,即使我看到子变量确实存在,if条件也总是返回false.看来.vars变量只能查询根变量,而不能查询像foo.test这样的子变量.

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.

在FreeMarker中,foo.barfoo["bar"]相同,但是在[]内部,您可以具有一个求值的任意表达式. em>转换为字符串.因此,您要查找的表达式只是foo[var].

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].

顺便说一句,您的宏尝试执行的操作只是${foo[var]!bar[var]}

BTW, what your macro tries to do is just ${foo[var]!bar[var]}