Freemarker: Dynamic interpolation of sub variables

a 夏天 提交于 2019-12-20 06:12:19

问题


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

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