在springboot中,推薦使用的模板引擎是Thymeleaf模板引擎,它提供了完美的Spring MVC的支持。下面就簡單的介紹一下Thymeleaf模板引擎的使用。
在controller層中,使用在類上使用@controller注解,注意的是,這里不是@restController注解,因為@restController注解是將結果作為json字符串進行返回的,並不是調用模板。
方法中,注入參數,Model model。然后同springmvc中的modelandview一樣,model也提供了屬性方法:addAttribute(“”,“”)。
下面是在html頁面的一些操作
- 引入Thymeleaf
在html標簽中加入名稱空間,將頁面轉換成動態的頁面
<html xmlns:th="http://www.thymeleaf.org">
轉換之后有一點需要注意,就是對於靜態資源的訪問也變了,靜態資源需要通過th:src=“@{path}”進行訪問。
- 訪問model中的數據,所有動態資源需要加上th前綴
需要在標簽中使用th:text="${singlePerson.age}進行訪問,感覺不是很方便,以后還是盡量使用ajax進行異步操作吧
<h2 th:text="${singlePerson.age}"></h2>
- 數據迭代
<ul> <li th:each="person:${list}"> <h1 th:text="${person.name}"></h1> </li> </ul>
- 數據的判斷
<ul th:if="${#lists.isEmpty(list)}"> <li th:each="person:${list}"> <h1 th:text="${person.name}"></h1> </li> </ul>
通過${#lists.isEmpty(list)}表達式判斷是否集合list為空。
Thymeleaf支持>,<,>=,<=,!=等作為比較條件,同時也支持將SpringEL表達式用於條件之中,不過這個我沒學過,具體就不知道怎么用了。
- 在JavaScript中訪問model
<script type="text/javascript" th:inline="javascript"> window.onload=function(){ alert([[${singlePerson.name}]]); } </script>
這里需要注意的是,在script標簽中,需要加入th:inline=“javascript”去聲明在下面的javascript中使用到了model的內容。
暫時就先記這么多,需要用的時候,再不定期補充。