Spring Boot+Thymeleaf学习

添加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知识点

参考资料——thymeleaf官网

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章