[英]using freemarker and spring to construct templates
我是 freemarker 的新手。 我有一個 spring 應用程序,我打算與 freemarker 一起使用。 模板將存儲在數據庫中,並根據登錄名,我想從數據庫中檢索模板。 誰能告訴我如何在spring中配置freemarker並在構建模板后將html標簽作為字符串獲取。 我做了谷歌搜索,但我無法理解。
我嘗試到這個水平。 在春天我已經做到了這個水平。 最后我想要一個字符串中的 html 標簽。
// Spring freemarker specific code
Configuration configuration = freemarkerConfig.getConfiguration();
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
// My application specific code
String temp = tempLoader.getTemplateForCurrentLogin();
謝謝。
要將您發布的代碼片段聯系在一起,您可以執行以下操作:
// 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);
這個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.