My FreeMarker method returns a string with ${variable} — how to force FreeMarker to parse that?

这一生的挚爱 提交于 2019-12-12 13:04:58

问题


I've created a class that implements TemplateMethodModelEx from FreeMarker. Pretend the exec() function returns a String: "Hello ${username}"

I assign the class to a method in the data model:

dataModel.put("myMethod", myClassInstance);
dataModel.put("username", "John Doe");

My HTML template looks like this:

<p>${myMethod()}</p>

Which means that the following output is generated, when the template is processed:

<p>Hello ${username}</p>

Since there is actually a username value in my data model, I'd rather want the output to be:

<p>Hello John Doe</p>

How do I tell FreeMarker to parse the result of myMethod()? I tried both ?eval and ?interpret and both fail to accomplish what I want. Is this possible with FreeMarker?


回答1:


You need to remove ${} from a string to use ?eval. Return username as a string from your method and use ?eval or get variable from .vars.

<p>${classInstance.myMethod()?eval}</p>

or

<p>${.vars[classInstance.myMethod()]}</p>

If you want to return not just a variable name but a string with an expression (e.g. "Hello ${username}") from the method then use ?interpret.

<#assign inlineTemplate = classInstance.myMethod()?interpret>
<@inlineTemplate />


来源:https://stackoverflow.com/questions/25545966/my-freemarker-method-returns-a-string-with-variable-how-to-force-freemarke

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