Thymeleaf語法總結 | 筆記分享

Thymeleaf語法總結

1、Thymeleaf介紹

Thymeleaf是Spring boot推薦使用的模版引擎,直接以html顯示,先後端能夠很好的分離。

 

2、Thymeleaf語法(Thymeleaf3)

在使用Thymeleaf時頁面要引入名稱空間: xmlns:th="http://www.thymeleaf.org"
 
一、th屬性,經常使用th屬性以下:
    1)th:text:文本替換;
<h1 th:text="${session.vel2}"></h1>
    2)th:utext:支持html的文本替換。
    3)th:value:屬性賦值  
    4)th:each:遍歷循環元素
//每次遍歷都會產生th:each所標註的標籤以及內部標籤 

<tr th:each="user : ${users}">
  <td th:text="${user.name}">Onions</td>
  <td th:text="${user.age}">2.41</td>
</tr>
    5)th:if:判斷條件,相似的還有th:unless,th:switch,th:case
<div th:if="true"> 你填的是true </div> //這裏引用了一個th:if指令,跟vue中的v-if相似
    6)th:insert:代碼塊引入,相似的還有th:replace,th:include,經常使用於公共代碼塊提取的場景
    7)th:fragment:定義代碼塊,方便被th:insert引用
    8)th:object:聲明變量,通常和*{}一塊兒配合使用,達到偷懶的效果。
<h2 th:object="${user}">   <p>Name: <span th:text="*{name}">Jack</span>.</p>   <p>Age: <span th:text="*{age}">21</span>.</p>   <p>friend: <span th:text="*{friend.name}">Rose</span>.</p> </h2>
    9)th:attr:設置標籤屬性,多個屬性能夠用逗號分隔
例子:

前端HTML

<!DOCTYPE html><!--名稱空間-->

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head> <meta charset="UTF-8"> <title>Thymeleaf 語法</title>
</head>
<body> <h2>ITDragon Thymeleaf 語法</h2> <!--th:text 設置當前元素的文本內容,經常使用,優先級不高--> <p th:text="${thText}" /> <p th:utext="${thUText}" /> <!--th:value 設置當前元素的value值,經常使用,優先級僅比th:text高--> <input type="text" th:value="${thValue}" /> <!--th:each 遍歷列表,經常使用,優先級很高,僅此於代碼塊的插入--> <!--th:each 修飾在div上,則div層重複出現,若只想p標籤遍歷,則修飾在p標籤上--> <div th:each="message : ${thEach}"> <!-- 遍歷整個div-p,不推薦--> <p th:text="${message}" /> </div> <div> <!--只遍歷p,推薦使用--> <p th:text="${message}" th:each="message : ${thEach}" /> </div> <!--th:if 條件判斷,相似的有th:switch,th:case,優先級僅次於th:each, 其中#strings是變量表達式的內置方法--> <p th:text="${thIf}" th:if="${not #strings.isEmpty(thIf)}"></p> <!--th:insert 把代碼塊插入當前div中,優先級最高,相似的有th:replace,th:include,~{} :代碼塊表達式 --> <div th:insert="~{grammar/common::thCommon}"></div> <!--th:object 聲明變量,和*{} 一塊兒使用--> <div th:object="${thObject}"> <p>ID: <span th:text="*{id}" /></p><!--th:text="${thObject.id}"--> <p>TH: <span th:text="*{thName}" /></p><!--${thObject.thName}--> <p>DE: <span th:text="*{desc}" /></p><!--${thObject.desc}--> </div>
</body>
</html>

後臺controller:

@Controller public class ThymeleafController { @RequestMapping("thymeleaf") public String thymeleaf(ModelMap map) { map.put("thText", "th:text 設置文本內容 <b>加粗</b>"); map.put("thUText", "th:utext 設置文本內容 <b>加粗</b>"); map.put("thValue", "thValue 設置當前元素的value值"); map.put("thEach", Arrays.asList("th:each", "遍歷列表")); map.put("thIf", "msg is not null"); map.put("thObject", new ThObject(1L, "th:object", "用來偷懶的th屬性")); return "grammar/thymeleaf"; } }

 

二、標準表達式語法:

  • ${...} 變量表達式,Variable Expressions
  • @{...} 連接表達式,Link URL Expressions
  • #{...} 消息表達式,Message Expressions
  • ~{...} 代碼塊表達式,Fragment Expressions
  • *{...} 選擇變量表達式,Selection Variable Expressions
  • ~{...} 代碼塊表達式,支持兩種語法結構

    推薦:~{templatename::fragmentname}
    支持:~{templatename::#id}
 
templatename:模版名,Thymeleaf會根據模版名解析完整路徑:/resources/templates/templatename.html,要注意文件的路徑。
fragmentname:片斷名,Thymeleaf經過th:fragment聲明定義代碼塊,即:th:fragment="fragmentname"
id:HTML的id選擇器,使用時要在前面加上#號,不支持class選擇器。

代碼塊表達式的使用

代碼塊表達式須要配合th屬性(th:insert,th:replace,th:include)一塊兒使用。
th:insert:將代碼塊片斷整個插入到使用了th:insert的HTML標籤中,
th:replace:將代碼塊片斷整個替換使用了th:replace的HTML標籤中,
th:include:將代碼塊片斷包含的內容插入到使用了th:include的HTML標籤中,

#{...} 消息表達式

消息表達式通常用於國際化的場景。

@{...} 連接表達式

連接表達式好處
無論是靜態資源的引用,form表單的請求,凡是連接均可以用@{...} 。這樣能夠動態獲取項目路徑,即使項目名變了,依然能夠正常訪問
#修改項目名,連接表達式會自動修改路徑,避免資源文件找不到 server.context-path=/itdragon
連接表達式結構
無參:@{/xxx}
有參:@{/xxx(k1=v1,k2=v2)} 對應url結構:xxx?k1=v1&k2=v2
引入本地資源:@{/項目本地的資源路徑}
引入外部資源:@{/webjars/資源在jar包中的路徑}
列舉:
<link th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet"> <link th:href="@{/main/css/itdragon.css}" rel="stylesheet"> <form class="form-login" th:action="@{/user/login}" th:method="post" > <a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a> <a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>

 

${...} 變量表達式功能

1、能夠獲取對象的屬性和方法
2、可使用ctx,vars,locale,request,response,session,servletContext內置對象
3、可使用dates,numbers,strings,objects,arrays,lists,sets,maps等內置方法(重點介紹)

經常使用的內置對象

1、ctx :上下文對象。
2、vars :上下文變量。
3、locale:上下文的語言環境。
4、request:(僅在web上下文)的 HttpServletRequest 對象。
5、response:(僅在web上下文)的 HttpServletResponse 對象。
6、session:(僅在web上下文)的 HttpSession 對象。
7、servletContext:(僅在web上下文)的 ServletContext 對象
這裏以經常使用的Session舉例,用戶刊登成功後,會把用戶信息放在Session中,Thymeleaf經過內置對象將值從session中獲取。
// java 代碼將用戶名放在session中 session.setAttribute("userinfo",username); // Thymeleaf經過內置對象直接獲取 th:text="${session.userinfo}"

經常使用的內置方法

1、strings:字符串格式化方法,經常使用的Java方法它都有。好比:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等
2、numbers:數值格式化方法,經常使用的方法有:formatDecimal等
3、bools:布爾方法,經常使用的方法有:isTrue,isFalse等
4、arrays:數組方法,經常使用的方法有:toArray,length,isEmpty,contains,containsAll等
5、lists,sets:集合方法,經常使用的方法有:toList,size,isEmpty,contains,containsAll,sort等
6、maps:對象方法,經常使用的方法有:size,isEmpty,containsKey,containsValue等
7、dates:日期方法,經常使用的方法有:format,year,month,hour,createNow等
 
 1 <!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head> 2 <meta charset="UTF-8"> 3 <title>ITDragon Thymeleaf 內置方法</title></head><body> 4 <h2>ITDragon Thymeleaf 內置方法</h2> 5 <h3>#strings </h3> 6 <div th:if="${not #strings.isEmpty(itdragonStr)}" > 7 <p>Old Str : <span th:text="${itdragonStr}"/></p> 8 <p>toUpperCase : <span th:text="${#strings.toUpperCase(itdragonStr)}"/></p> 9 <p>toLowerCase : <span th:text="${#strings.toLowerCase(itdragonStr)}"/></p> 10 <p>equals : <span th:text="${#strings.equals(itdragonStr, 'itdragonblog')}"/></p> 11 <p>equalsIgnoreCase : 12 <span th:text="${#strings.equalsIgnoreCase(itdragonStr, 'itdragonblog')}"/></p> 13 <p>indexOf : <span th:text="${#strings.indexOf(itdragonStr, 'r')}"/></p> 14 <p>substring : <span th:text="${#strings.substring(itdragonStr, 2, 8)}"/></p> 15 <p>replace : <span th:text="${#strings.replace(itdragonStr, 'it', 'IT')}"/></p> 16 <p>startsWith : <span th:text="${#strings.startsWith(itdragonStr, 'it')}"/></p> 17 <p>contains : <span th:text="${#strings.contains(itdragonStr, 'IT')}"/></p> 18 </div> 19 20 <h3>#numbers </h3> 21 <div> 22 <p>formatDecimal 整數部分隨意,小數點後保留兩位,四捨五入: 23 <span th:text="${#numbers.formatDecimal(itdragonNum, 0, 2)}"/></p> 24 <p>formatDecimal 整數部分保留五位數,小數點後保留兩位,四捨五入: 25 <span th:text="${#numbers.formatDecimal(itdragonNum, 5, 2)}"/></p> 26 </div> 27 28 <h3>#bools </h3> 29 <div th:if="${#bools.isTrue(itdragonBool)}"> 30 <p th:text="${itdragonBool}"></p> 31 </div> 32 33 <h3>#arrays </h3> 34 <div th:if="${not #arrays.isEmpty(itdragonArray)}"> 35 <p>length : <span th:text="${#arrays.length(itdragonArray)}"/></p> 36 <p>contains : <span th:text="${#arrays.contains(itdragonArray, 5)}"/></p> 37 <p>containsAll : <span th:text="${#arrays.containsAll(itdragonArray, itdragonArray)}"/></p> 38 </div> 39 <h3>#lists </h3> 40 <div th:if="${not #lists.isEmpty(itdragonList)}"> 41 <p>size : <span th:text="${#lists.size(itdragonList)}"/></p> 42 <p>contains : <span th:text="${#lists.contains(itdragonList, 0)}"/></p> 43 <p>sort : <span th:text="${#lists.sort(itdragonList)}"/></p> 44 </div> 45 <h3>#maps </h3> 46 <div th:if="${not #maps.isEmpty(itdragonMap)}"> 47 <p>size : <span th:text="${#maps.size(itdragonMap)}"/></p> 48 <p>containsKey : <span th:text="${#maps.containsKey(itdragonMap, 'thName')}"/></p> 49 <p>containsValue : <span th:text="${#maps.containsValue(itdragonMap, '#maps')}"/></p> 50 </div> 51 <h3>#dates </h3> 52 <div> 53 <p>format : <span th:text="${#dates.format(itdragonDate)}"/></p> 54 <p>custom format : <span th:text="${#dates.format(itdragonDate, 'yyyy-MM-dd HH:mm:ss')}"/></p> 55 <p>day : <span th:text="${#dates.day(itdragonDate)}"/></p> 56 <p>month : <span th:text="${#dates.month(itdragonDate)}"/></p> 57 <p>monthName : <span th:text="${#dates.monthName(itdragonDate)}"/></p> 58 <p>year : <span th:text="${#dates.year(itdragonDate)}"/></p> 59 <p>dayOfWeekName : <span th:text="${#dates.dayOfWeekName(itdragonDate)}"/></p> 60 <p>hour : <span th:text="${#dates.hour(itdragonDate)}"/></p> 61 <p>minute : <span th:text="${#dates.minute(itdragonDate)}"/></p> 62 <p>second : <span th:text="${#dates.second(itdragonDate)}"/></p> 63 <p>createNow : <span th:text="${#dates.createNow()}"/></p> 64 </div></body></html>

 

 
 1 @RequestMapping("varexpressions")public String varexpressions(ModelMap map) { 2 map.put("itdragonStr", "itdragonBlog"); 3 map.put("itdragonBool", true); 4 map.put("itdragonArray", new Integer[]{1,2,3,4}); 5 map.put("itdragonList", Arrays.asList(1,3,2,4,0)); 6 Map itdragonMap = new HashMap(); 7 itdragonMap.put("thName", "${#...}"); 8 itdragonMap.put("desc", "變量表達式內置方法"); 9 map.put("itdragonMap", itdragonMap); 10 map.put("itdragonDate", new Date()); 11 map.put("itdragonNum", 888.888D); return "grammar/varexpressions"; 12 }
相關文章
相關標籤/搜索