1. 模板字符串
@Test
public void test() throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("username", "lisi");
String templateString = "欢迎${username}登录!";
StringWriter result = new StringWriter();
Template t = new Template("template", new StringReader(templateString), new Configuration(Configuration.VERSION_2_3_23));
t.process(map, result);
System.out.println(result.toString());
}
2.模板文件
比如:有一个echarts的option模板(option.ftl)
{
title: {
text: 'ECharts示例'
},
tooltip: {
},
legend: {
data: ['销量']
},
xAxis: {
data: ${xAxisData}
},
yAxis: {
},
series: [{
name: '销量',
type: 'bar',
data: ${seriesData}
}]
}
数据:xAxisData为["衬衫","羊毛衫","雪纺衫","裤子","鞋子","袜子"],seriesData为[5,20,36,10,10,20]
生成结果为:
代码如下:
@Test
public void test2() throws Exception {
// 设置Configuration
Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
configuration.setDefaultEncoding("UTF-8");
// 根据classloader加载模板文件
configuration.setClassLoaderForTemplateLoading(ClassLoader.getSystemClassLoader(), "/");
// 生成模板对象
String templateFileName = "option.ftl";
Template template = configuration.getTemplate(templateFileName);
StringWriter stringWriter = new StringWriter();
Map<String, Object> map = new HashMap<String, Object>();
// 一般开发用List<String>,List<Integer>会多一些,这里为了简单,直接就用数组了
String[] xAxisData = new String[]{"衬衫", "羊毛衫", "雪纺衫",
"裤子", "鞋子","袜子"};
map.put("xAxisData", JSON.toJSONString(xAxisData));
int[] seriesData = new int[]{5, 20, 36, 10, 10, 20};
map.put("seriesData", JSON.toJSONString(seriesData));
template.process(map, stringWriter);
System.out.println(stringWriter.getBuffer().toString());
}
项目目录结构如图:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kittycoder</groupId>
<artifactId>FreemarkerDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>4.12</junit.version>
<freemarker.version>2.3.23</freemarker.version>
<fastjson.version>1.2.21</fastjson.version>
</properties>
<dependencies>
<!-- test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
</dependencies>
</project>
参考链接: