Spring Boot + Thymeleaf学习

添加Thymeleaf依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Spring Boot默认存放模板页面的路径在src/main/resources/templates

<html>标签中引入:

1
<html xmlns:th="http://www.thymeleaf.org">

条件语句 th:if

1
2
3
 <li th:if="${session.user != null}">
<a href="/publish">发布</a>
</li>

迭代器 th:each

遍历questions集合

1
2
3
<div class="media" th:each="question:${questions}">
...
</div>

图片地址 th:src

1
2
3
4
<a href="#">
<img class="media-object img-circle"
th:src="${question.user.avatarUrl}">
</a>

文本显示 th:text

1
2
<span th:text="${#dates.format(question.gmtCreate,'yyyy.MM.dd')}"></span>
<!-- #dates.format 定义时间格式,question.gmtCreate是定义的时间,右边的是格式 例:yyyy是2019,MM是09,dd是23-->

th:value

用来页面回显

1
2
3
4
<div class="form-group">
<label for="title">问题标题(简单扼要):</label>
<input type="text" class="form-control" th:value="${title}" id="title" name="title" placeholder="问题标题...">
</div>

部分后台代码

1
2
3
4
5
6
7
8
9
@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

1
2
3
4
<li th:class="${pagination.page==page}? 'active' : ''">
...
</li>
<!--三目运算符,条件成立时,设置class为active,否则设置为空-->

链接拼接 th:href

1
2
<a  th:href="@{/(page=${page})}" th:text="${page}"></a>
<!--@{} ${} -->
1
2
3
4
 <a th:href="@{'/profile/'+${section}(page=${2})}" aria-label="Previous">
...
</a>
<!-- 例如要拼接这样的地址:~/profile/questions?page=2 -->

引用片段 th:insert

/templates目录下新建一个名为navigation.html的文件,内容是:

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>

<div th:fragment="nav">
<!-- 放入要被引用的片段 —— 类似多个页面都是相同的代码这种 -->
...
</div>

</body>
</html>

使用(在页面中引入)

1
2
3
4
5
<body>
...
<div th:insert="~{navigation:: nav}"></div>
<!--navigation是用来装片段的文件名称,nav是片段名-->
</body>

以上是做项目过程中用到的部分Thymeleaf知识点

参考资料——thymeleaf官网