Thymeleaf
spring集成了Thymeleaf模板引擎,本文对此作些许介绍
方言
Thymeleaf提供了灵活接口,允许使用方定制自己的方言。因此在自定义方言之前,有必要先了解标准方言。
标准表达式
${...} : 变量表达式.
*{...} : 区域选择表达式.
#{...} : 消息国际化表达式.
@{...} : 链接表达式.
~{...} : 代码段表达式.
Variable
变量表达式通常是OGNL
${session.user.name}
Thymeleaf
<span th:text="${book.author.name}">
等价SpringEL 或 OGNL
((Book)context.getVariable("book")).getAuthor().getName()
从上下文读取迭代
<li th:each="book : ${books}">
选择表达式
类似下面这样,通常是在子区域内选择当前上下文,类似go模板中的.
*{customer.name}
完整示例
<div th:object="${book}">
...
<span th:text="*{title}">...</span>
...
</div>
等价于
{
// th:object="${book}"
final Book selection = (Book) context.getVariable("book");
// th:text="*{title}"
output(selection.getTitle());
}
国际化
通常会依赖键定位读取本地.properties
文件中对应语言的消息
#{main.title}
#{message.entrycreated(${entryId})}
在模板中是这样
<table>
...
<th th:text="#{header.address.city}">...</th>
<th th:text="#{header.address.country}">...</th>
...
</table>
当然键亦可使用变量
#{${config.adminWelcomeKey}(${session.user.name})}
链接表达式
基于webserver上下文为根路径生成,假定根路径/myapp
<a th:href="@{/order/list}">...</a>
对应
<a href="/myapp/order/list">...</a>
保持会话
<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="@{~/contents/main}">...</a>
基于协议的绝对路径
<a th:href="@{//static.mycompany.com/res/initial}">...</a>
<a th:href="@{http://www.mycompany.com/main}">...</a>
片段表达式
有时部会添加或替换一段java代码 th:insert
或th:replace
<div th:insert="~{commons :: main}">...</div>
或
<div th:with="frag=~{footer :: #main/text()}">
<p th:insert="${frag}">
</div>
本作品采用《CC 协议》,转载必须注明作者和本文链接