一.介绍
开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了。SpringBoot支持如下页面模板语言
- Thymeleaf
- FreeMarker
- Velocity
- Groovy
- JSP
二.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Spring Boot默认存放模板页面的路径在src/main/resources/templates或者src/main/view/templates,这个无论是使用什么模板语言都一样,当然默认路径是可以自定义的,不过一般不推荐这样做。另外Thymeleaf默认的页面文件后缀是.html。
三.基本语法
首先要在改写html标签
<html xmlns:th="http://www.thymeleaf.org">
这样的话才可以在其他标签里面使用th:*这样的语法.这是下面语法的前提.
1).获取变量值
<p th:text="'Hello!, ' + ${name} + '!'" >3333</p>
获取变量值用$
符号,$
表达式只能写在th标签内部,不然不会生效,上面例子就是使用th:text标签的值替换p标签里面的值.
2).引入URL
Thymeleaf对于URL的处理是通过语法@{…}来处理的
<a th:href="@{http://blog.youkuaiyun.com/u012706811}">绝对路径</a>
<a th:href="@{/}">相对路径</a>
<a th:href="@{css/bootstrap.min.css}">Content路径,默认访问static下的css文件夹</a>
类似的标签有:th:href
和th:src
3).字符串替换
通过字符串拼接操作完成:
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
4).运算符
在表达式中可以使用各类算术运算符,例如+, -, *, /, %
<p th:with="isEven=(${prodStat.count} % 2 == 0)"></p>
5).条件
- if / unless
Thymeleaf中使用th:if和th:unless属性进行条件判断,下面的例子中,标签只有在th:if中条件成立时才显示:
<a th:if="${myself=='yes'}" > </i> </a>
<a th:unless=${session.user != null} th:href="@{/login}" >Login</a>
th:unless于th:if恰好相反,只有表达式中的条件不成立,才会显示其内容。
- Switch
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
</div>
默认属性default可以用*表示:
<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>
</div>
6).循环
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
</tr>
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
</table>
<p>
<a href="../home.html" th:href="@{/}">Return to home</a>
</p>
</body>