freemarker
是一個用Java開發的模板引擎
常用的java模板引擎還有哪些?
Jsp
、Freemarker
、Thymeleaf
、Velocity
等。
1. 快速入門
1.1 創建工程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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1.2 編輯application.yml
server:
port: 8088
spring:
application:
name: test-freemarker
# freemarker配置
freemarker:
cache: false #關閉模板緩存,方便測試
settings:
template_update_delay: 0 #檢查模板更新延遲時間,設置為0表示立即檢查,如果時間大於0會有緩存不方便進行模板測試
template-loader-path: classpath:/templates
charset: UTF-8
check-template-location: true
suffix: .ftl
content-type: text/html
expose-request-attributes: true
expose-session-attributes: true
request-context-attribute: request
1.3 創建模型類
在freemarker
的測試工程下創建模型類型用於測試
package com.example.demo.model;
import lombok.Data;
import lombok.ToString;
import java.util.Date;
import java.util.List;
/**
* @author john
* @date 2019/12/20 - 16:52
*/
@Data
@ToString
public class Student {
private String name;//姓名
private int age;//年齡
private Date birthday;//生日
private Float money;//錢包
private List<Student> friends;//朋友列表
private Student bestFriend;//最好的朋友
}
1.4 創建模板
在 src/main/resources
下創建templates
,此目錄為freemarker
的默認模板存放目錄。
在templates
下創建模板文件test1.ftl
,模板中的${name}
最終會被freemarker
替換成具體的數據。
<html>
<head>
<title>hello world!</title>
</head>
<body>
hello ${name}
</body>
</html>
1.5 創建controller
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
/**
* @author john
* @date 2019/12/20 - 16:54
*/
@Controller
@RequestMapping("freemarker")
public class FreemarkerController {
@GetMapping("/test1")
public String freemarker(Map<String, Object> map) {
map.put("name", "java");
//返回模板文件名稱
return "test1";
}
}
1.6 測試
2. FreeMarker 基礎
2.1 數據模型
Freemarker
靜態化依賴數據模型和模板,下邊定義數據模型:
下邊方法形參map
即為freemarker
靜態化所需要的數據模型,在map
中填充數據:
@GetMapping("/test1")
public String freemarker(Map<String, Object> map) {
//向數據模型放數據
map.put("name", "john");
Student stu1 = new Student();
stu1.setName("小明");
stu1.setAge(18);
stu1.setMoney(1000.86f);
stu1.setBirthday(new Date());
Student stu2 = new Student();
stu2.setName("小紅");
stu2.setMoney(200.1f);
stu2.setAge(19);
// stu2.setBirthday(new Date());
List<Student> friends = new ArrayList<>();
friends.add(stu1);
stu2.setFriends(friends);
stu2.setBestFriend(stu1);
List<Student> stus = new ArrayList<>();
stus.add(stu1);
stus.add(stu2);
//向數據模型放數據
map.put("stus", stus);
//准備map數據
HashMap<String, Student> stuMap = new HashMap<>();
stuMap.put("stu1", stu1);
stuMap.put("stu2", stu2);
//向數據模型放數據
map.put("stu1", stu1);
//向數據模型放數據
map.put("stuMap", stuMap);
//返回模板文件名稱
return "test1";
}
2.2 List指令
本節定義freemarker
模板,模板中使用freemarker
的指令,關於freemarker
的指令需要知道:
1、注釋,即<#‐‐和‐‐>,介於其之間的內容會被freemarker忽略
2、插值(Interpolation):即${..}部分,freemarker會用真實的值代替${..}
3、FTL指令:和HTML標記類似,名字前加#予以區分,Freemarker會解析標簽中的表達式或邏輯。
4、文本,僅文本信息,這些不是freemarker的注釋、插值、FTL指令的內容會被freemarker忽略解析,直接輸出內
容。
在test1.ftl模板中使用list指令遍歷數據模型中的數據:
<html>
<head>
<title>hello world!</title>
</head>
<body>
<table>
<tr>
<td>序號</td>
<td>姓名</td>
<td>年齡</td>
<td>錢包</td>
</tr>
<#list stus as stu>
<tr>
<td>${stu_index + 1}</td>
<td>${stu.name}</td>
<td>${stu.age}</td>
<td>${stu.money}</td>
</tr>
</#list>
</table>
</body>
</html>
輸出
_index:得到循環的下標,使用方法是在stu后邊加"_index",它的值是從0開始
2.3 遍歷Map數據
-
數據模型
使用map
指令遍歷數據模型中的stuMap
。 -
模板
<html>
<head>
<title>hello world!</title>
</head>
<body>
輸出stu1的學生信息:<br/>
姓名:${stuMap.stu1.name}<br/>
年齡:${stuMap.stu1.age}<br/>
遍歷輸出兩個學生信息:<br/>
<table>
<tr>
<td>序號</td>
<td>姓名</td>
<td>年齡</td>
<td>錢包</td>
</tr>
<#list stuMap?keys as k>
<tr>
<td>${k_index + 1}</td>
<td>${stuMap[k].name}</td>
<td>${stuMap[k].age}</td>
<td>${stuMap[k].money}</td>
</tr>
</#list>
</table>
</body>
</html>
輸出結果
2.4 if指令
if 指令即判斷指令,是常用的FTL指令,freemarker在解析時遇到if會進行判斷,條件為真則輸出if中間的內容,否
則跳過內容不再輸出。
1、數據模型:
使用list指令中測試數據模型。
2、模板:
<html>
<head>
<title>hello world!</title>
</head>
<body>
<table>
<tr>
<td>姓名</td>
<td>年齡</td>
<td>錢包</td>
</tr>
<#list stus as stu>
<tr>
<td <#if stu.name =='小明'>style="background:red;"</#if>>${stu.name}</td>
<td>${stu.age}</td>
<td>${stu.money}</td>
</tr>
</#list>
</table>
</body>
</html>
2.5 運算符
-
算數運算符
FreeMarker
表達式中完全支持算術運算,FreeMarker
支持的算術運算符包括:+, - , * , / , % -
邏輯運算符 邏輯運算符有如下幾個: 邏輯與:&& 邏輯或:|| 邏輯非:! 邏輯運算符只能作用於布爾值,否則將產生錯誤
-
比較運算符 表達式中支持的比較運算符有如下幾個:
- 1 =或者==:判斷兩個值是否相等.
- 2 !=:判斷兩個值是否不等.
- 3 >或者gt:判斷左邊值是否大於右邊值
- 4 >=或者gte:判斷左邊值是否大於等於右邊值
- 5 <或者lt:判斷左邊值是否小於右邊值
- 6 <=或者lte:判斷左邊值是否小於等於右邊值
注意: =和!=可以用於字符串,數值和日期來比較是否相等,但=和!=兩邊必須是相同類型的值,否則會產生錯誤,而且
FreeMarker
是精確比較,"x","x ","X"是不等的.其它的運行符可以作用於數字和日期,但不能作用於字符串,大部分的時候,使用gt等字母運算符代替>會有更好的效果,因為 FreeMarker會把>解釋成FTL標簽的結束字符,當然,也可以使用括號來避免這種情況,如:<#if (x>y)>
2.6 空值處理
1、判斷某變量是否存在使用 “??” 用法為:variable??,如果該變量存在,返回true,否則返回false
例:為防止stus為空報錯可以加上判斷如下:
<#if stus??>
<#list stus as stu>
<tr>
<td>${stu.name}</td>
<td>${stu.age}</td>
<td>${stu.money}</td>
</tr>
</#list>
</#if>
2、缺失變量默認值使用 “!” 使用!要以指定一個默認值,當變量為空時顯示默認值。
例: ${name!''}
表示如果name
為空顯示空字符串。
如果是嵌套對象則建議使用()
括起來。
例: ${(stu.bestFriend.name)!''}
表示,如果stu
或bestFriend
或name
為空默認顯示空字符串。
2.7 內建函數
內建函數語法格式: 變量+?+函數名稱
1、和到某個集合的大小
${集合名?size}
<html>
<head>
<title>hello world!</title>
</head>
<body>
<table>
<tr>
<td>姓名</td>
<td>年齡</td>
<td>錢包</td>
</tr>
<#if stus??>
stus集合的大小是${stus?size}
<#list stus as stu>
<tr>
<td>${stu.name}</td>
<td>${stu.age}</td>
<td>${stu.money}</td>
</tr>
</#list>
</#if>
</table>
</body>
</html>
2、日期格式化
顯示年月日: ${today?date}
顯示時分秒:${today?time}
顯示日期+時間:${today?datetime} <br>
自定義格式化: ${today?string("yyyy年MM月")}
<#if stus??>
<#list stus as stu>
<tr>
<td>${stu.name}</td>
<td>${stu.age}</td>
<td>${stu.money}</td>
<td>${(stu.birthday?date)!''}---${(stu.birthday?time)!''}---${(stu.birthday?datetime)!''}
---${(stu.birthday?string("yyyy年MM月"))!''}</td>
</tr>
</#list>
</#if>
3、內建函數c
map.put("point", 102920122);
point
是數字型,使用${point}
會顯示這個數字的值,不並每三位使用逗號分隔。
如果不想顯示為每三位分隔的數字,可以使用c函數將數字型轉成字符串輸出
${point?c}
4、將json字符串轉成對象
一個例子:
其中用到了 assign
標簽,assign
的作用是定義一個變量。
<#assign text="{'bank':'工商銀行','account':'10101920201920212'}" />
<#assign data=text?eval />
開戶行:${data.bank} 賬號:${data.account}