Thymeleaf

  • 一款Java模板引擎,能够处理HTML,XML,JS,CSS等,类似JSP,Freemarker

  • 自然模板,原型即页面

  • 语法优雅易懂 OGNL,SpringEL
  • 遵循web标准,支持HTML5.
Thymeleaf 标准方言(五种)
1
2
3
4
5
${...} 变量表达式
*{...} 选择表达式
#{...} i18n表达式
@{...} 链接表达式
~{...} 片段表达式

如何识别

  • <span th:text="...">
  • <span data-th-text="...">

变量表达式

语法:${...}

<span th:text="${book.author.name}">

消息表达式(也称为文本外部化 国际化)

语法:#{...}

<th th:text="#{header.address.city}">...</th>

选择表示式

语法:*{...}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div th:object="${book}">
<span th:text="*{title}">...</span>
</div>

<form action="/users" method="post" th:object="${user}">
<input type="hidden" name="id" th:value="*{id}">
<br>
名称:<br>
<input type="text" name="name" th:value="*{name}">
<br>
Email:<br>
<input type="text" name="email" th:value="*{email}">
<input type="submit" value="submit">
</form>

与变量表达式区别:它们是在当前选择的对象而不是整个上下文变量映射上执行。

即上面的title 实际是book.title user.id

链接表达式

语法:@{...}

分段表达式

语法:th:insert 或 th:replace

1
2
3
4
5
header.html
<div th:fragment="header1111">
<h1>Thymeleaf in action</h1>
<a href="/users/list">welcome to site</a>
</div>
1
2
3
引用上面header
<div th:replace="~{fragment/footer :: footer1111}"></div>
位置+“::”+ fragment名字

设置属性值

语法:th:attr

1
2
<form action="1.html" th:attr="action=@{/sub}">
</form>

迭代器

基本的迭代 th:each

1
2
3
4
5
<li th:each="book:${books}" ></li>
<tr>
<td th:text="${book.id}"></td>
<td th:text="${book.site}"></td>
</tr>

条件语句

<th:if> <th:unless> <th:switch>