Configure
- 开发配置:
#开发阶段选择关闭缓存; spring.thymeleaf.cache=false spring.thymeleaf.mode=LEGACYHTML5
- 引入支持不严格检测html的依赖:NoheHTML是一个html扫描器和标签补全器;
<!-- 取消html严格验证 --> <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> </dependency> <dependency> <groupId>org.unbescape</groupId> <artifactId>unbescape</artifactId> <version>1.1.6.RELEASE</version> </dependency>
- 引入命名空间:
<html xmlns:th="http://www.thymeleaf.org">
语法规则
- th:text,改变当前元素里面的文本内容
- 表达式
${} 变量表达式,获取对象属性、调用方法、使用内置的基本对象(ctx、request、response、session)、内置的工具对象
*{} 变量选择表达式,跟 ${} 一样,配合 th:object 使用
@{} URL表达式,定义 url 链接
~{} 片段引用表达式
#{} 获取国际化内容 - 标准变量表达式:${msg},msg两段可以有空格,大小写敏感;
<p th:text="#{home.welcome}">Welcome to our grocery store!</p>
- 选择变量表达式:*{msg},配合标准变量表达式简化属性获取;
<div th:object="${session.user}"> <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p><!-- 获取属性 --> <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p> </div>
- URL表达式:@{msg},取动态变量用;
<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) --> <a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a> <!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) --> <a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a> <!-- Will produce '/gtvg/order/3/details' (plus rewriting) --> <a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>
3.Attributes
- action
<form action="subscribe.html" th:action="@{/subscribe}"> <fieldset> <input type="text" name="email" /> <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/> </fieldset> </form>
- each:Note that the
prod
iter variable is scoped to the<tr>
element, which means it is available to inner tags like<td>
.<table> <tr> <th>NAME</th> <th>PRICE</th> <th>IN STOCK</th> <th>COMMENTS</th> </tr> <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'"> <td th:text="${prod.name}">Onions</td> <td th:text="${prod.price}">2.41</td> <td th:text="${prod.inStock}? #{true} : #{false}">yes</td> <td> <span th:text="${#lists.size(prod.comments)}">2</span> comment/s <a href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:unless="${#lists.isEmpty(prod.comments)}">view</a> </td> </tr> </table>
属性 th:each 包含一些状态变量:
- index:当前迭代器下标,0 开始;
- count:当前迭代器下标,1 开始;
- size:迭代器变量的元素总数;
- current:迭代器的每一个迭代变量;
- even/odd:判断是否当前迭代为奇数、偶数次;
- first:判断当前是否是第一次迭代;
- last:判断当前是否是最后一次迭代;
- href & if:产品带有品论信息时显示;
<a href="comments.html" th:href="@{/product/comments(prodId=${prod.id})}" th:if="${not #lists.isEmpty(prod.comments)}">view</a>
- unless
<span th:unless="${gender == '0'}"> 男 </span> <span th:unless="${gender == '1'}"> 女 </span>
- switch/case
<div th:switch="${gender}"> <p th:case="1">male</p> <p th:case="0">female</p> </div>
- object
- text
- value
- attr