依赖
<freemarker.version>2.3.28</freemarker.version>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>
简单使用
String dir="/XXX/src/main/resources";
Configuration conf = new Configuration();
//加载模板文件(模板的路径)
conf.setDirectoryForTemplateLoading(new File(dir));
// 加载模板
Template template = conf.getTemplate("/demo.ftl");
// 定义数据
Map root = new HashMap();
root.put("world", "Hello World");
// 定义输出
Writer out = new FileWriter(dir + "/demo.html");
template.process(root, out);
System.out.println("转换成功");
out.flush();
out.close();
bean配置
<bean id="freemarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
<property name="templateLoaderPath" value="/WEB-INF/views/message"/>
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop>
<prop key="default_encoding">UTF-8</prop>
<prop key="locale">zh_CN</prop>
</props>
</property>
</bean>
@Component
public class FreeMarkerTemplateUtil {
private static final Logger log = LoggerFactory.getLogger(FreeMarkerTemplateUtil.class);
@Resource
private Configuration freemarkerConfiguration;
public String processTemplateIntoString(String fileName, Map<String,Object> data){
try {
Template t = freemarkerConfiguration.getTemplate(fileName);
String body = FreeMarkerTemplateUtils.processTemplateIntoString(t, data);
return body;
} catch (IOException e) {
log.error(e.getMessage(),e);
throw new RuntimeException(e.toString(),e);
} catch (TemplateException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e.toString(),e);
}
}
}
字符串加载
如果我想把模板存放到数据库中,可以实现吗?答案是肯定的。在这里可以使用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");
网友评论