Thymeleaf标准表达式
变量表达式:${}
选择表达式:*{}
消息表达式:#{}
链接表达式:@{}
片段表达式:~{}
变量表达式
获取返回的字段:
获取book对象的author字段对象的name字段值
<span th:text = "${book.author.name}"></span>
循环迭代:
books是一个collection,从中依次获取对象遍历。
<li th:each="book : ${books}"></li>
选择表达式
在指定的model中获取字段:
获取book对象的title字段
获取book对象的author字段
<div th:object="${book}">
<span th:text="*{title}"></span>
<span th:text="*{author}"></span>
</div>
使用th:object可以指定所选的模型,使用*{property}确定为某个字段。
消息表达式
消息表达式可以获取.properties文件中的配置信息。
<table>
<th th:text="#{header.address.city}"></th>
<th th:text="#{header.address.country}"></th>
</table>
链接表达式
可以简化链接的生成难度。
<a th:href="@{/order/list}"></a>
如果项目部署在myapp下,那么上述标记等价于:
<a href="/myapp/order/list">...</a>
通过链接表达式可以实现cookie没有打开的时候的session维护:
<a href="/myapp/order/list;jsessionid=23fa31abd41ea093">...</a>
实现url的带参数的创建:
<a th:href="@{/order/details(id=${orderId},type=${orderType})}">...</a>
等价于:
<a href="/myapp/order/details?id=23&type=online">...</a>
也可以使用相对地址:
<a th:href="@{../documents/report}">...</a>
<a th:href="@{~/contents/main}">...</a>
片段表达式
可以使用片段表达式插入,替换,引入其他的模板
<div th:insert="~{commons :: main}">...</div>
<div th:with="frag=~{footer :: #main/text()}">
<p th:insert="${frag}">
</div>
字面及操作
文本:'one', 'Another one'
数字:0, 34, 3.0, 12.3
布尔:true, false
空:null
字面标记:one, sometext, main
文本操作符:
连接:+
混合:| The name is ${name} |
数学运算符:
四则:+,-,*,/,%
负号:-
布尔运算:
二进制操作:and or
否定:!,not
关系运算:
比较:>,>=,<,<=
等价比较:==,!=
条件操作:
if-then: (if)? (then)
if-then-else: (if)?(then):(else)
default: (value)?:(defaultValue)
表达式预处理
使用__可以实现预处理:
#{selection.__${sel.code}__}
优先处理sel.code
常见的标记
1. 使用th:text替换内容
<p th:text="#{msg.welcome}">Welcome everyone!</p>
2. 使用th:each循环遍历
<li th:each="book : ${books}" th:text="${book.title}">En las Orillas del Sar</li>
3. 使用标记辅助确定其值
<form th:action="@{/createOrder}">
<input type="button" th:value="#{form.submit}" />
<a th:href="@{/admin/users}">