本文介绍了我的FreeMarker方法返回带有$ {variable}的字符串-如何强制FreeMarker解析该字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个从FreeMarker实现 TemplateMethodModelEx 的类.假设 exec()函数返回一个字符串:"Hello $ {username}"

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");

我的HTML模板如下:

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>

如何告诉FreeMarker解析 myMethod()的结果?我尝试了?eval ?interpret ,都无法完成我想要的. FreeMarker可以做到这一点吗?

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?

推荐答案

您需要从字符串中删除${}才能使用?eval.从方法中以字符串形式返回username,并使用?eval或从.vars获取变量.

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>

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

如果您不仅要从方法中返回变量名,还要返回带有表达式的字符串(例如"Hello $ {username}"),请使用?interpret.

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 />

这篇关于我的FreeMarker方法返回带有$ {variable}的字符串-如何强制FreeMarker解析该字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 16:56