freemarker模板

一.什么是 Apache FreeMarker。

1.Apache FreeMarker™是一个模板引擎:一个Java库,用于根据模板和更改数据生成文本输出(HTML网页,电子邮件,配置文件,源代码等)。模板是用FreeMarker模板语言(FTL)编写的,这是一种简单的专用语言(不像PHP这样的完整编程语言)

特征

FreeMarker的一些亮点:

  • 强大的模板语言:条件块,迭代,赋值,字符串和算术运算和格式,宏和函数,包括其他模板,默认情况下转义(可选)等等
  • 多用途和轻量级:零依赖性,任何输出格式,可以从任何地方(可插入)加载模板,许多配置选项
  • 国际化/本地化感知:区域设置敏感数字和日期/时间格式,本地化模板变体。
  • XML处理功能:将XML DOM-s放入数据模型并遍历它们,甚至以声明方式处理它们
  • 多功能数据模型:Java对象通过可插拔适配器作为变量树暴露给模板,该适配器决定模板如何看待它们。

二.springboot中快速使用freemarker模板。

1.在Pom文件中引入相应的jar;

1
2
3
4
5
6
7
8


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>


2.在项目的的resources文件下创建freemarker文件夹用于存放freemarker模板文件

文件后缀名为:.ftl

3.在配置文件application.yml中配置freemarker的属性

1
2
3
4
5
6
7
8
9
10
11
12


spring:
freemarker:
suffix: .ftl
template-loader-path: file:D:/project-demo-template/project-demo-freemarker/target/classes/freemarker/
mvc:
view:
suffix: .ftl
prefix: /templates/


template-loader-path为模板文件存放的地址

注:在使用freemarker模板时请注意关闭模板缓存:

spring.freemarker.cache=false

到此整个流程已经完成。

4.当freemarker模板不用于页面展示时如:用于xml格式模板用于写xml数据

则需要配置其模板初始化

一般在Service层使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28


@Service
public class FreemarkerService {
private final Configuration configuration;
//init

@Autowired
public FreemarkerService(Configuration configuration) {
this.configuration = configuration;
}
/**
*name:为模板名称如:test.ftl,map表参数
*configuration.getTemplate(name) 获取模板
* FreeMarkerTemplateUtils.processTemplateIntoString(template, map) 给模板赋值并转换为String;
* 相当于model.addAttribute("",""); reutrn "xx.jsp" 一样;
* 只不过前者是附后拿到相应的类型数据 后者是在页面展示
*/
public String processTemplateIntoString(String name, Map<String, Object> map) throws IOException, TemplateException {
Template template = configuration.getTemplate(name);
map.put("name", "这是一个名称");
String str = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
return str;
}

}