Freemarker 入门
新建maven项目,引入依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
在resources下新建模板hello.ftl
<#list userList as value>
my name ${value}
</#list>
从模板读取数据,渲染到另外一个文件中
Configuration configuration = new Configuration(Configuration.getVersion());
Writer out = null;
try {
File srcFile = new File(TEMPLATE_PATH);
System.out.println(srcFile.getAbsolutePath());
System.out.println(TEMPLATE_PATH);
// step2 获取模版路径
configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
// step3 创建数据模型
Map<String, Object> dataMap = new HashMap<String, Object>();
ArrayList userList = new ArrayList();
userList.add("lgm");
userList.add("wsf");
userList.add("wsl");
userList.add("zmy");
userList.add("lsq");
dataMap.put("userList", userList);
// step4 加载模版文件
Template template = configuration.getTemplate("hello.ftl");
// step5 生成数据
File docFile = new File(TEMPLATE_PATH + "\\" + "hello.txt");
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
// step6 输出文件
template.process(dataMap, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != out) {
out.flush();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
替换后的结果
my name lgm
my name wsf
my name wsl
my name zmy
my name lsq
从字符串中读取模板
StringTemplateLoader loader = new StringTemplateLoader();
configuration.setTemplateLoader(loader);
loader.putTemplate("tpm", "<#list userList as value>\n" +
" my name ${value}\n" +
"</#list>");
// step3 创建数据模型
Map<String, Object> dataMap = new HashMap<String, Object>();
ArrayList userList = new ArrayList();
userList.add("lgm");
userList.add("wsf");
userList.add("wsl");
userList.add("zmy");
userList.add("lsq");
dataMap.put("userList", userList);
// step4 加载模版文件
Template template = configuration.getTemplate("tpm");
out = new StringWriter();
// step6 输出文件
template.process(dataMap, out);
System.out.println(out.getBuffer().toString());
替换后结果跟之前一样
my name lgm
my name wsf
my name wsl
my name zmy
my name lsq
posted on 2020-06-19 08:44 liguangming 阅读(119) 评论(0) 编辑 收藏 举报