问题
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