导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
controller
@RequestMapping(value = "/greeting")
public ModelAndView test(ModelAndView mv) {
mv.setViewName("/greeting");
mv.addObject("title","欢迎使用Thymeleaf!");
return mv;
}
HTML
默认只要我们把HTML页面放在classpath:/templates/
,thymeleaf就能自动渲染;
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link th:href="@{/css/1.css}" rel="stylesheet"/>
</head>
<body>
<p th:text="'Hello, ' + ${title}" /><br/>
<script th:src="@{/js/jquery/1.11.0/jquery.js}"></script>
<script>
$(function(){
alert("page load finish.");
});
</script>
</body>
</html>
常用标签:
th:text
用来将内容输出到所在标签的body中
代码举例<li th:text="${game.id}"></li>
意思是li的内容是game.id这个数据,用${}来选择
另外还可以选择变量输出
<p>Today is: <span th:text="${today}">25 September 2018</span></p>
<span th:text="${#calendars.format(today,'dd MMMM yyyy')}">25 September 2018</span>
这里的${today} 用来引用 today 变量,第二个是输出不同的日期模式
其次还有输出URL,输出布尔表达式
<a href="games/list.html" th:href="@{/games/list}">Games List</a>
--输出URL
<div th:if="${user.isAdmin()} == false">
--输出布尔表达式
th:each
<ul th:each="game : ${games}">
<li th:text="${game.id}"></li>
<li th:text="${game.name}"></li>
<li th:text="${game.type}"></li>
<li><img th:src="${game.image}"/></li>
<li th></li>
</ul>
结合上面ModelAndView的代码段来看 ,games是我的list数据集合,game相当于是我的一个引用,可以用这种方式遍历输出。
th:switch
判断用户类型,不同类型不一样的显示
<a href="comments.html" th:href="@{/comments(prodId=${prod.id})}" th:unless="${#lists.isEmpty(prod.comments)}">view</a>
<a href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:if="${not #lists.isEmpty(prod.comments)}">view</a>
<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> --默认的 case 相当于default
</div>
th:if
只有在th:if中条件成立时才显示:
th:unless
th:unless于th:if恰好相反,只有表达式中的条件不成立,才会显示其内容。
参考资料:
ModelAndView绑定数据模型配合Thymeleaf渲染数据用法学习
可能出现的问题:
springboot控制器返回字符串,不能返回页面