gpt4 book ai didi

java - 将 freemarker 模板写入字符串输出

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:00:38 30 4
gpt4 key购买 nike

我想在字符串中输出 freemarker 模板。我有一个 freemarker 模板文件 commonTemplate.ftl

<div>
<div>
<h1>${userDetails.name}</h1>
${userDetails.birthday} ${userDetails.id}
</div>
</div>

以及填充模型并将输出打印到控制台 App.java 的 Java 代码。

public class App {

private Service service = new Service();


public void execute() {
Configuration configuration = prepareConfiguration();
// Load templates from resources/templatess.
configuration.setClassForTemplateLoading(App.class, "/templates");

try {
Template template = configuration.getTemplate("commonTemplate.ftl");

// Console output
Writer out = new OutputStreamWriter(System.out);
template.process(prepareData(), out);
out.flush();

} catch (IOException | TemplateException e) {
throw new RuntimeException(e);
}
}

private Configuration prepareConfiguration() {
Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
configuration.setDefaultEncoding("UTF-8");
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
configuration.setLogTemplateExceptions(false);
return configuration;
}

private Map<String, Object> prepareData() {
Model model = service.getModel();
Map<String, Object> data = new HashMap<String, Object>();
data.put("userDetails", model.getUserDetails());
return data;
}
}

它适用于控制台输出。

<div>
<div>
<h1>john Doe</h1>
1990-01-10T12:11+01:00[Europe/Prague] 1
</div>
</div>

最佳答案

希望这能奏效。

// write the freemarker output to a StringWriter 
StringWriter stringWriter = new StringWriter();
template.process(prepareData(), stringWriter);

// get the String from the StringWriter
String string = stringWriter.toString();

关于java - 将 freemarker 模板写入字符串输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41977252/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com