[英]using freemarker and spring to construct templates
I am new to freemarker.我是 freemarker 的新手。 I have a spring application that I am planning to use with freemarker.我有一个 spring 应用程序,我打算与 freemarker 一起使用。 Templates will be stored in database and based on the login, I want to retrieve the template from database.模板将存储在数据库中,并根据登录名,我想从数据库中检索模板。 Can any one tell me how to configure the freemarker in spring and get the html tags as a string after constructing the template.谁能告诉我如何在spring中配置freemarker并在构建模板后将html标签作为字符串获取。 I did googling but I could not understand much.我做了谷歌搜索,但我无法理解。
I tried till this level.我尝试到这个水平。 In spring I have done till this level.在春天我已经做到了这个水平。 Finally I want html tags in a string.最后我想要一个字符串中的 html 标签。
// Spring freemarker specific code
Configuration configuration = freemarkerConfig.getConfiguration();
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
// My application specific code
String temp = tempLoader.getTemplateForCurrentLogin();
Thanks.谢谢。
To tie together the bits of code you posted, you can do something like this:要将您发布的代码片段联系在一起,您可以执行以下操作:
// you already have this bit
String templateText = tempLoader.getTemplateForCurrentLogin();
// now programmatically instantiate a template
Template t = new Template("t", new StringReader(templateText), new Configuration());
// now use the Spring utility class to process it into a string
// myData is your data model
String output = FreeMarkerTemplateUtils.processTemplateIntoString(template, myData);
This java method will process the freemarker template and will give html tags as String after constructing the template.这个java方法将处理freemarker模板,并在构建模板后将html标签作为字符串。
public static String processFreemarkerTemplate(String fileName) {
StringWriter stringWriter = new StringWriter();
Map<String, Object> objectMap = new HashMap<>();
Configuration cfg = new Configuration(Configuration.VERSION_2_3_24);
try {
cfg.setDirectoryForTemplateLoading(new File("path/of/freemarker/template"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
Template template = cfg.getTemplate(fileName);
template.process(objectMap, stringWriter);
} catch (IOException | TemplateException e) {
e.printStackTrace();
} finally {
if (stringWriter != null) {
try {
stringWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return stringWriter.toString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.