FreeMarker Template Language (FTL)
文档:
- en: https://freemarker.apache.org/docs/index.html
- cn: http://freemarker.foofun.cn/index.html
依赖
org.freemarker
freemarker
2.3.31
使用示例
package com.pengshiyu;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class FreemarkerDemo {
public static void main(String[] args) throws Exception {
// 第一步:配置freemarker
Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
// 设置模板路径
configuration.setDirectoryForTemplateLoading(new File("./"));
// 第二步:加载模板
Template template = configuration.getTemplate("template.ftl");
// 第三步:模板数据
Map data = new HashMap();
data.put("name", "汤姆");
data.put("age", 23);
// 第四步:渲染输出
// 输出到字符串
Writer stringWriter = new StringWriter();
template.process(data, stringWriter);
stringWriter.close();
System.out.println(stringWriter.toString());
// 输出到文件
Writer fileWriter = new FileWriter(new File("hello.html"));
template.process(data, fileWriter);
fileWriter.close();
}
}
模板文件 template.ftl
Demo
${name}
${age}
输出结果 hello.html
Demo
汤姆
23
问题及解决
报错
严重: DefaultObjectWrapper.incompatibleImprovements was set to the object returned by Configuration.getVersion(). That defeats the purpose of incompatibleImprovements, and makes upgrading FreeMarker a potentially breaking change. Also, this probably won't be allowed starting from 2.4.0. Instead, set incompatibleImprovements to the highest concrete version that's known to be compatible with your application.
解决方式
// 不推荐使用
Configuration configuration = new Configuration(Configuration.getVersion());
// 修改为:
Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
模板语法
Hello ${name}
is Tom
is Jack
not is Tom
${item.name} ${item.age}
参考 FreeMarker 快速入门 SpringBoot整合FreeMarker模板报错