作為一個模板框架,freemarker的功能還是很強大的。在模板處理方面,freemarker有多種形式,最常見的方式是將模板文件放在一個統一的文件夾下面,如下形式:
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File("templates"));
如果我想把模板存放到數據庫中,可以實現嗎?答案是肯定的。在這里可以使用StringTemplateLoader來加載模板內容。主要的代碼實現如下所示:
Configuration cfg = new Configuration();
StringTemplateLoader stringLoader = new StringTemplateLoader();
String templateContent="hello ${name}!";
stringLoader.putTemplate("myTemplate",templateContent);
cfg.setTemplateLoader(stringLoader);
Template template = cfg.getTemplate("myTemplate","utf-8");