SpringBoot整合FreeMarker模板引擎
點擊上方藍色字體,選擇“標星公眾號”
優(yōu)質文章,第一時間送達
? 作者?|??天喬巴夏丶
來源 |? urlify.cn/YVfqa2
FreeMarker是什么?
一款模板引擎。即一種基于模板和要改變的數據, 并用來生成輸出文本(HTML網頁,電子郵件,配置文件,源代碼等)的通用工具。
在模板中,你可以專注于如何展現(xiàn)數據, 而在模板之外可以專注于要展示什么數據,體現(xiàn)就是:模板+ 數據模型 = 輸出。

快速開始
pom.xml確定導入FreeMarker依賴包
????
????????org.springframework.boot
????????spring-boot-starter-freemarker
????
配置application.yml相關配置
spring:
??freemarker:
????settings:
??????classic_compatible:?true?#處理空值
??????datetime_format:?yyy-MM-dd?HH:mm
??????number_format:?0.##
????suffix:?.ftl
????template-loader-path:
??????-?classpath:/templates
在templates目錄下放置
.ftl文件,意為freemarker templates layer。編寫Controller,將模型存入request中:
@Controller
public?class?TestController{
????@GetMapping("test")
????public?String?test(HttpServletRequest?request){
????????List?users?=?new?LinkedList<>();
????????for(int?i?=?0;?i?10;?i?++){
????????????User?user?=?new?User();
????????????user.setId((long)i);
????????????user.setUsername("name?=?"?+?i);
????????????users.add(user);
????????}
????????request.setAttribute("users",users);
????????return?"test";
????}
}
簡單使用FreeMarker的標簽指令:
<#list?users>
????Users:
????
????????<#items?as?user>
????????????- ${user.id}--${user.username}
????????????#items>
????
<#else>
????no?users!
#list>
模板一覽
${...}:FreeMarker將會輸出真實的值來替換大括號內的表達式,被稱為插值表達式。
<#../>:FTL標簽,以#開頭,自定義標簽則以@開頭。
常用指令
條件指令:if、elseif、else
<#if?animals.python.price?
??Pythons?are?cheaper?than?elephants?today.
<#elseif?animals.elephant.price?
??Elephants?are?cheaper?than?pythons?today.
<#else>
??Elephants?and?pythons?cost?the?same?today.
#if>
list指令
list?指令的一般格式為:?<#list sequence as loopVariable> repeatThis。?repeatThis?部分將會在給定的?sequence?遍歷時在每一項中重復, 從第一項開始,一個接著一個。在所有的重復中,?loopVariable?將持有當前遍歷項的值。這個變量僅存在于?<#list ...>?和?<#list>?標簽內。
We?have?these?animals:
??<#list?animals?as?animal>
????${animal.name} ${animal.price}?Euros
??#list>
sequence?可以是任意表達式, 比如我們可以列表顯示示例數據模型中的水果,就像這樣:
<#list?misc.fruits?as?fruit>
??- ${fruit}
#list>
上面示例中的一個問題是如果我們有0個水果,它仍然會輸出一個空的?,而不是什么都沒有。要避免這樣的情況,可以這么來使用?list:
<#list?misc.fruits>
??Fruits:
??
????<#items?as?fruit>
??????- ${fruit}<#sep>?and#sep>
????#items>
??
<#else>
??We?have?no?fruits.
#list>
include指令
使用?include?指令, 我們可以在模板中插入其他文件的內容。
如果需要在每個頁面的下方都顯示版權信息,可以將版權信息單獨放在頁面文件?copyright_footer.html?中:
Copyright?(c)?2000?"http://www.acmee.com">Acmee?Inc,
All?Rights?Reserved.
使用時,用include引入該文件即可:
??Test?page
??Test?page
??Blah?blah...
??<#include?"/copyright_footer.html">
內建函數
內建函數很像子變量(如果了解Java術語的話,也可以說像方法), 它們并不是數據模型中的東西,是 FreeMarker 在數值上添加的。為了清晰子變量是哪部分,使用??(問號)代替?.(點)來訪問它們。
所有內建函數參考:http://freemarker.foofun.cn/ref_builtins.html
處理不存在的變量
一個不存在的變量和一個是null值的變量, 對于FreeMarker來說是一樣的。
不論在哪里引用變量,都可以指定一個默認值來避免變量丟失這種情況, 通過在變量名后面跟著一個?!(嘆號,譯者注)和默認值。就像下面的這個例子,當?user?不存在于數據模型時, 模板將會將?user?的值表示為字符串?"visitor"。(當?user?存在時, 模板就會表現(xiàn)出?${user}?的值):
Welcome?${user!"visitor"}!
也可以在變量名后面通過放置????來詢問一個變量是否存在。將它和?if?指令合并, 那么如果?user?變量不存在的話將會忽略整個問候的代碼段:
<#if?user??>Welcome?${user}!
#if>
自定義指令
使用macro定義宏
未帶參數宏調用
<#macro?greet>
??"+2">Hello?Joe!
#macro>
<#--未帶參數宏調用-->
????<@greet>@greet>
帶參數宏調用
<#macro?greet_2?person>
????"+2">Hello?${person}!
#macro>
<#--帶參數宏調用-->
????<@greet_2?person="天喬巴夏"/>
嵌套調用
<#macro?nest_test>
????<#nested?>
#macro>
<#--嵌套調用-->????
????<@nest_test>
????????hyh
????????@nest_test>
使用TemplateDirectiveModel擴展。
這部分可以參考我發(fā)在碼云上的代碼:https://gitee.com/tqbx/springboot-samples-learn/tree/master/spring-boot-freemarker。
????@Override
????public?void?execute(DirectiveHandler?handler)?throws?Exception?{
????????//?獲取參數
????????String?username?=?handler.getString("username");
????????String?city?=?handler.getString("city");
????????//?處理參數
????????String?template?=?"{}來自{}.";
????????String?format?=?StrUtil.format(template,?username,?city);
????????//?傳回去
????????handler.put("result",format).render();
????}
@Configuration
public?class?FreeMarkerConfig?{
????@Autowired
????StringTemplate?stringTemplate;
????@Autowired
????private?freemarker.template.Configuration?configuration;
????@PostConstruct
????public?void?setUp()?{
????????configuration.setSharedVariable("timeAgo",?new?TimeAgoMethod());
????????configuration.setSharedVariable("strstr",?stringTemplate);
????}
}
<@strstr?username="hyh"?city="杭州">
????${result}
????@strstr>
粉絲福利:實戰(zhàn)springboot+CAS單點登錄系統(tǒng)視頻教程免費領取
???
?長按上方微信二維碼?2 秒 即可獲取資料
感謝點贊支持下哈?
