# Thymeleaf語法
## xmlns:th
```
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<!--/*@thymesVar id="name" type="java.lang.String"*/-->
<p th:text="'Hello!, ' + ${name} + '!'" >3333</p>
</body>
</html>
```
注意:`<html xmlns:th="http://www.thymeleaf.org">`用于解析模板里的`tf`標簽
這樣的話才可以在其他標簽里面使用th:*這樣的語法.這是下面語法的前提.
## 獲取變量值
`<p th:text="'Hello!, ' + ${name} + '!'" >3333</p>`
可以看出獲取變量值用$符號,對于javaBean的話使用變量名.屬性名方式獲取,這點和EL表達式一樣.
另外$表達式只能寫在th標簽內部,不然不會生效,上面例子就是使用th:text標簽的值替換p標簽里面的值,至于p里面的原有的值只是為了給前端開發時做展示用的.這樣的話很好的做到了前后端分離.
## 引入URL
Thymeleaf對于URL的處理是通過語法@{…}來處理的
```
<a th:href="@{http://blog.csdn.net/u012706811}">絕對路徑</a>
<a th:href="@{/}">相對路徑</a>
<a th:href="@{css/bootstrap.min.css}">Content路徑,默認訪問static下的css文件夾</a>
```
類似的標簽有:th:href和th:src
## 字符串替換
很多時候可能我們只需要對一大段文字中的某一處地方進行替換,可以通過字符串拼接操作完成:
`<span th:text="'Welcome to our application, ' + ${user.name} + '!'">`
一種更簡潔的方式是:
`<span th:text="|Welcome to our application, ${user.name}!|">`
當然這種形式限制比較多,|…|中只能包含變量表達式${…},不能包含其他常量、條件表達式等。
## 運算符
在表達式中可以使用各類算術運算符,例如+, -, *, /, %
`th:with="isEven=(${prodStat.count} % 2 == 0)"`
邏輯運算符>, <, <=,>=,==,!=都可以使用,唯一需要注意的是使用<,>時需要用它的HTML轉義符:
```
th:if="${prodStat.count} > 1"
th:text="'Execution mode is ' + ( (${execMode} == 'dev')? 'Development' : 'Production')"
```
## 條件
### if/unless
Thymeleaf中使用th:if和th:unless屬性進行條件判斷,下面的例子中,標簽只有在th:if中條件成立時才顯示:
```
<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
```
th:unless于th:if恰好相反,只有表達式中的條件不成立,才會顯示其內容。
### Switch
Thymeleaf同樣支持多路選擇Switch結構:
```
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
</div>
```
默認屬性default可以用*表示:
```
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p>
</div>
```
## 循環
渲染列表數據是一種非常常見的場景,例如現在有n條記錄需要渲染成一個表格
,該數據集合必須是可以遍歷的,使用th:each標簽:
```
<body>
<h1>Product list</h1>
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
</tr>
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
</table>
<p>
<a href="../home.html" th:href="@{/}">Return to home</a>
</p>
</body>
```
可以看到,需要在被循環渲染的元素(這里是)中加入th:each標簽,其中th:each=”prod : ${prods}”意味著對集合變量prods進行遍歷,循環變量是prod在循環體中可以通過表達式訪問。
th:each屬性用于迭代循環,語法:th:each="obj,iterStat:${objList}"
迭代對象可以是java.util.List,java.util.Map,數組等;
iterStat稱作狀態變量,屬性有:
```
index:當前迭代對象的index(從0開始計算)
count: 當前迭代對象的index(從1開始計算)
size:被迭代對象的大小
current:當前迭代變量
even/odd:布爾值,當前循環是否是偶數/奇數(從0開始計算)
first:布爾值,當前循環是否是第一個
last:布爾值,當前循環是否是最后一個
```
```
<ol>
<li>List循環:
<table border="1">
<tr>
<th>用戶名</th>
<th>郵箱</th>
<th>管理員</th>
<th>狀態變量:index</th>
<th>狀態變量:count</th>
<th>狀態變量:size</th>
<th>狀態變量:current.userName</th>
<th>狀態變量:even</th>
<th>狀態變量:odd</th>
<th>狀態變量:first</th>
<th>狀態變量:last</th>
</tr>
<tr th:each="user,userStat : ${list}">
<td th:text="${user.userName}">Onions</td>
<td th:text="${user.email}">test@test.com.cn</td>
<td th:text="${user.isAdmin}">yes</td>
<th th:text="${userStat.index}">狀態變量:index</th>
<th th:text="${userStat.count}">狀態變量:count</th>
<th th:text="${userStat.size}">狀態變量:size</th>
<th th:text="${userStat.current.userName}">狀態變量:current</th>
<th th:text="${userStat.even}">狀態變量:even****</th>
<th th:text="${userStat.odd}">狀態變量:odd</th>
<th th:text="${userStat.first}">狀態變量:first</th>
<th th:text="${userStat.last}">狀態變量:last</th>
</tr>
</table>
</li>
<li>Map循環:
<div th:each="mapS:${map}">
<div th:text="${mapS}"></div>
</div>
</li>
<li>數組循環:
<div th:each="arrayS:${arrays}">
<div th:text="${arrayS}"></div>
</div>
</li>
</ol>
```
## Utilities工具
為了模板更加易用,Thymeleaf還提供了一系列Utility對象(內置于Context中),可以通過#直接訪問:`
```
● #dates
● #calendars
● #numbers
● #strings
● arrays
● lists
● sets
● maps
● …
```
下面用一段代碼來舉例一些常用的方法:
### date
```
/*
* Format date with the specified pattern
* Also works with arrays, lists or sets
*/
${#dates.format(date, 'dd/MMM/yyyy HH:mm')}
${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}
${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}
${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}
/*
* Create a date (java.util.Date) object for the current date and time
*/
${#dates.createNow()}
/*
* Create a date (java.util.Date) object for the current date (time set to 00:00)
*/
${#dates.createToday()}
string
/*
* Check whether a String is empty (or null). Performs a trim() operation before check
* Also works with arrays, lists or sets
*/
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)}
/*
* Check whether a String starts or ends with a fragment
* Also works with arrays, lists or sets
*/
${#strings.startsWith(name,'Don')} // also array*, list* and set*
${#strings.endsWith(name,endingFragment)} // also array*, list* and set*
/*
* Compute length
* Also works with arrays, lists or sets
*/
${#strings.length(str)}
/*
* Null-safe comparison and concatenation
*/
${#strings.equals(str)}
${#strings.equalsIgnoreCase(str)}
${#strings.concat(str)}
${#strings.concatReplaceNulls(str)}
/*
* Random
*/
${#strings.randomAlphanumeric(count)}
```
## 在文本中使用表達式
當然,我們同樣可以在標簽內賦值。
`<p>Hello, [[${session.user.name}]]!</p>`
效果和下面一樣:
`<p>Hello, <span th:text="${session.user.name}">Sebastian</span>!</p>`
`[[…]]`之間的內容可以被賦值。為了使其生效,必須在此標簽或者任何父標簽上有th:inline屬性。此屬性有三種值(text , javascript and none)。text屬性的用法:
`<p th:inline="text">Hello, [[${session.user.name}]]!</p>`
也可以在父標簽上有此屬性:
~~~
<body th:inline="text">
...
<p>Hello, [[${session.user.name}]]!</p>
...
</body>
~~~
## 在javaScript中使用表達式
### 給js變量賦值
表達式同樣可以在javascript中使用。先用屬性聲明一下:`javascript ( th:inline=”javascript” )`,然后我們開始在js中聲明變量:
~~~
<script th:inline="javascript">
/*<![CDATA[*/
...
var username = /*[[${session.user.name}]]*/ 'Sebastian';
...
/*]]>*/
</script>
~~~
`/*[[…]]*/`表達式的理解如下:
`/*…*/`中的內容在用瀏覽器打開靜態 網頁時,會被忽略。Sebastian會在瀏覽器中顯示。Thymeleaf解析時,會解析`/*[[…]]*/`的內容,并把獲得的值替換掉`/*[[…]]*/`里的內容。所以執行的結果如下:
~~~
<script th:inline="javascript">
/*<![CDATA[*/
...
var username = 'John Apricot';
...
/*]]>*/
</script>
~~~
你也可以不用注釋:
~~~
<script th:inline="javascript">
/*<![CDATA[*/
...
var username = [[${session.user.name}]];
...
/*]]>*/
</script>
~~~
這會讓它在靜態顯示時出現錯誤。
注意:引擎求值后注入是智能的,它可以智能賦值一下類型的數據。
~~~
Strings
Numbers
Booleans
Arrays
Collections
Maps
Beans (objects with getter and setter methods)
~~~
~~~
<script th:inline="javascript">
/*<![CDATA[*/
...
var user = /*[[${session.user}]]*/ null;
...
/*]]>*/
</script>
~~~
${session.user}會獲取一個user對象。寫入后如下:
~~~
<script th:inline="javascript">
/*<![CDATA[*/
...
var user = {'age':null,'firstName':'John','lastName':'Apricot',
'name':'John Apricot','nationality':'Antarctica'};
...
/*]]>*/
</script>
~~~
引擎同樣允許增加和刪除代碼塊,增加代碼塊:
~~~
var x = 23;
/*[+
var msg = 'This is a working application';
+]*/
var f = function() {
...
~~~
解析如下:
~~~
var x = 23;
var msg = 'This is a working application';
var f = function() {
...
~~~
刪除代碼塊:
~~~
var x = 23;
/*[- */
var msg = 'This is a non-working template';
/* -]*/
var f = function(){
...
~~~
解析如下:
~~~
var x = 23;
var f = function(){
...
~~~