添加Thymeleaf依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Spring Boot默認存放模板頁面的路徑在src/main/resources/templates
在<html>
標籤中引入:
<html xmlns:th="http://www.thymeleaf.org">
條件語句 th:if
<li th:if="${session.user != null}">
<a href="/publish">發佈</a>
</li>
迭代器 th:each
遍歷questions集合
<div class="media" th:each="question:${questions}">
...
</div>
圖片地址 th:src
<a href="#">
<img class="media-object img-circle"
th:src="${question.user.avatarUrl}">
</a>
文本顯示 th:text
<span th:text="${#dates.format(question.gmtCreate,'yyyy.MM.dd')}"></span>
<!-- #dates.format 定義時間格式,question.gmtCreate是定義的時間,右邊的是格式 例:yyyy是2019,MM是09,dd是23-->
頁面回顯 th:value
<div class="form-group">
<label for="title">問題標題(簡單扼要):</label>
<input type="text" class="form-control" th:value="${title}" id="title" name="title" placeholder="問題標題...">
</div>
部分後臺代碼
@PostMapping("/publish")
public String doPublish(
@RequestParam(value = "title", required = false) String title,
@RequestParam(value = "description", required = false) String description,
@RequestParam(value = "tag", required = false) String tag,
HttpServletRequest request,
Model model) {
...
}
<textarea>
標籤裏的回顯問題:要用th:text
才起作用,th:value
不起作用 不懂爲什麼??
設置樣式 th:class
<li th:class="${pagination.page==page}? 'active' : ''">
...
</li>
<!--三目運算符,條件成立時,設置class爲active,否則設置爲空-->
鏈接拼接 th:href
<a th:href="@{/(page=${page})}" th:text="${page}"></a>
<!--@{} ${} -->
<a th:href="@{'/profile/'+${section}(page=${2})}" aria-label="Previous">
...
</a>
<!-- 例如要拼接這樣的地址:~/profile/questions?page=2 -->
引用片段 th:insert
在/templates
目錄下新建一個名爲navigation.html
的文件,內容是:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="nav">
<!-- 放入要被引用的片段 —— 類似多個頁面都是相同的代碼這種 -->
...
</div>
</body>
</html>
使用(在頁面中引入)
<body>
...
<div th:insert="~{navigation:: nav}"></div>
<!--navigation是用來裝片段的文件名稱,nav是片段名-->
</body>
以上是做項目過程中用到的部分Thymeleaf知識點