jar
包:freemarker-gae-2.3.19
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreemarkerDemo {
public static void main(String[] args) throws IOException, TemplateException {
// 创建freemarker实例
Configuration conf = new Configuration();
// 设置模版 路径
String dir = "E:\\ws\\framework\\demo\\ftl\\";
// 设置模板的加载目录,这个路径必须写成绝对路径。
// 但是在实际的项目开发中,我们不可能使用这样一个路径,
// 因此,我们需要借助其他方法,例如springmvc中有FreeMarkerConfigurer这样的一个类
conf.setDirectoryForTemplateLoading(new File(dir));
// 设置将 [#]替代<#ftl>
conf.setTagSyntax(Configuration.SQUARE_BRACKET_TAG_SYNTAX);
// 指定模板,返回模板对象
Template template = conf.getTemplate("freemarker.html");
// 设置数据
Map<String, Object> root = new HashMap<String, Object>();
root.put("world", "你好世界");
root.put("cur_time", new Date());
Person person = new Person();
person.setName("张三");
Person person1 = new Person();
root.put("person", person);
root.put("person1", person1);
// 输出
Writer out = new FileWriter(new File(dir + "hello.html"));
// freemarker处理数据及模板并输出
template.process(root, out);
out.close();
}
}
模板:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
${world}
[#assign x ]
[#list ["1","2","3"] as n]
${n}
[/#list]
[/#assign]
${x+2}
${person.name}
${person1.name!".."}
${cur_time?string('yyyy-MM-dd')}
[#macro macroName source]
${source}
[/#macro]
[@macroName source=2 /]
</body>
</html>
生成的文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
你好世界
1
2
3
2
张三
..
2017-05-11
2
</body>
</html>