springboot~使用freemaker模版進行部署
實事上keycloak框架使用了freemaker進行頁面部署,在頁面上使用了vue進行了渲染,還是比較跟的上技術前沿的,只不過,keycloak沒有使用spring框架,可能是因為它是redhat公司推出的產品吧。
依賴引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- FreeeMarker模板引擎所需依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
配置文件
spring:
freemarker:
suffix: .ftl # 設置模板后綴名
content-type: text/html # 設置文檔類型
charset: UTF-8 # 設置頁面編碼格式
cache: false # 設置頁面緩存
template-loader-path: classpath:/templates # 設置ftl文件路徑
mvc:
static-path-pattern: /static # 設置靜態文件路徑,js,css等
添加模板
- resources/templates/template.ftl
<#macro registrationLayout bodyClass="默認值,子頁面沒有設置會使用這個值,子頁面設置后會覆蓋它">
<#--語法介紹:-->
<#--<#macro name param1 param2 ... paramN>--><!-- macro在模板里定義的變量,在子頁面中可以重寫變量的內容,它會反映的模板里-->
<#--<#nested loopvar1, loopvar2, ..., loopvarN>-->
<#--<p>${param1?cap_first}-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><#nested "head"></title>
</head>
<body>
<p>
${bodyClass}
</p>
<h1>FreeMaker模板頁面</h1>
<#nested "form">
</body>
</html>
</#macro>
添加頁面
- resources/templates/f1/list.ftl
<#import "../template.ftl" as layout>
<@layout.registrationLayout bodyClass="<span style='color:red'>修改模板里的變量</span>";section>
<#if section = "head">
列表
<#elseif section = "form">
<table border="1">
<tr>
<td>編號</td>
<td>名稱</td>
<td>年齡</td>
<td>操作</td>
</tr>
</table>
</#if>
</@layout.registrationLayout>
添加controller
@Controller
@RequestMapping("free")
public class F1Controller {
@RequestMapping("list")
public String selectUser(){
return "f1/list";
}
}
上面用到了freemaker中的宏macro,引用import,模塊嵌入nested ,首字母大寫內建函數?cap_first等知識點,大家如果看不懂,可以查以上相關資料。
頁面運行后的截圖

freemaker幾個內建函數
(1) 常用內建函數
- 處理字符串:
- ?substring 截取字符串,包頭不包尾(下標)
- ?cap_first 第一個字母大寫
- ?end_with 以什么字母結尾
- ?contains 是否包含目標字符串
- ?date datetime time 轉換成日期格式
- ?starts_with 以什么字母開頭
- ?index_of 返回某個指定的字符串值在字符串中首次出現的位置(下標)
- ?last_index_of 獲取指定字符出現的最后位置(下標)
- ?split 分隔
- ?trim 去兩端空格
- 處理數字:
- ?string x?string(“0.##”) 變成小數點后幾位
- ?round 四舍五入
- ?floor 去掉小數點
- ?ceiling 近1 變成整數
- 處理list:
- ?first: 取List值第一個值
- ?last: 取List值最后一個值
- ?seq_contains: 是否包含指定字符
- ?seq_index_of: 指定字符所在位置
- ?size: 集合大小
- ?reverse: 集合倒序排列
- ?sort: 對集合進行排序
- ?sort_by: 根據某一個屬性排序
- ?chunk: 分塊處理
- 其他:
- ?is_string: 是否為字符類型
- ?is_number: 是否為整數類型
- ?is_method: 是否為方法
- 判斷整個變量
- ?has_content: 判斷對象是否為空或不存在
- ?eval: 求值
(2) macro(宏指令)
- 調用:<@macro_name param />
<#macro 變量名 參數>
<#nested/>
</#macro>
(3) function(函數指令)
- 調用:$
<#function 變量名 參數>
<#return>
</#function>
浙公網安備 33010602011771號