java 将 freemarker 模板写入字符串输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41977252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:16:34 来源:igfitidea点击:
Write freemarker template to String output
提问by Yan Khonski
I would like to have freemarker template output in String. I have a freemarker template file commonTemplate.ftl.
我想在字符串中有 freemarker 模板输出。我有一个 freemarker 模板文件commonTemplate.ftl。
<div>
<div>
<h1>${userDetails.name}</h1>
${userDetails.birthday} ${userDetails.id}
</div>
</div>
And Java code which populates model and prints output to console App.java.
以及填充模型并将输出打印到控制台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;
}
}
It works for console output.
它适用于控制台输出。
<div>
<div>
<h1>john Doe</h1>
1990-01-10T12:11+01:00[Europe/Prague] 1
</div>
</div>
回答by Sainath Batthala
Hope this works.
希望这有效。
// 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();
回答by Yan Khonski
try {
Template template = configuration.getTemplate("commonTemplate.ftl");
Writer out = new StringWriter();
template.process(prepareData(), out);
System.out.println(out.toString());
} catch (IOException | TemplateException e) {
throw new RuntimeException(e);
}