这篇指南将介绍Thymeleaf模板技术的标准方言(Standard dialects)和Spring标准方言(SpringStandard dialects)的一些重要概念。
标准方言(Standard dialects)
Thymeleaf的可扩展性很强,它支持自定义你自己的模板属性集(或事件标签)、表达式、语法及应用逻辑,它更像一个模板引擎框架。
然而,秉着“开箱即用”的原则,Thymeleaf提供了满足大多数情况下的默认实现-标准方言(Standard and SpringStandard dialects)。你可以在模板中识别出这些被使用的标准方言,因为他们都以th属性开头,如
- <span th:text="...">
值得注意的是,Standard和SpringStandard方言的用法几乎相同,但是SpringStandard包括了Spring MVC集成的具体特征(比如用Spring Expression Language来替代OGNL)。
标准表达式语法(Standard Expression syntax)
大部分Thymeleaf属性允许它们的值被设置成或包含到表达式中,我们称之为标准表达式,
它们分为四类:
1.变量表达式
2.选择或星号表达式
3.文字国际化表达式
4.URL表达式
变量表达式
变量表达式即OGNL表达式或Spring EL表达式(在Spring术语中也叫model attributes)。如下所示:
- ${session.user.name}
- <span th:text="${book.author.name}">
- <li th:each="book : ${books}">
选择(星号)表达式
选择表达式很像变量表达式,不过它们用一个预先选择的对象来代替上下文变量容器(map)来执行,如下:- *{customer.name}
- <div th:object="${book}">
- ...
- <span th:text="*{title}">...</span>
- ...
- </div>
文字国际化表达式
文字国际化表达式允许我们从一个外部文件获取区域文字信息(.properties),用Key索引Value,还可以提供一组参数(可选).
- #{main.title}
- #{message.entrycreated(${entryId})}
- <table>
- ...
- <th th:text="#{header.address.city}">...</th>
- <th th:text="#{header.address.country}">...</th>
- ...
- </table>
URL表达式
URL表达式指的是把一个有用的上下文或回话信息添加到URL,这个过程经常被叫做URL重写。- @{/order/list}
- @{/order/details(id=${orderId})}
- @{../documents/report}
- <form th:action="@{/createOrder}">
- <a href="main.html" th:href="@{/main}">
字面量和操作
Thymeleaf有一组可用的字面量和操作。
- Literals:
- Text literals:
'one text'
,'Another one!'
,… - Number literals:
0
,34
,3.0
,12.3
,… - Boolean literals:
true
,false
- Null literal:
null
- Literal tokens:
one
,sometext
,main
,…
- Text literals:
- Text operations:
- String concatenation:
+
- Literal substitutions:
|The name is ${name}|
- String concatenation:
- Arithmetic operations:
- Binary operators:
+
,-
,*
,/
,%
- Minus sign (unary operator):
-
- Binary operators:
- Boolean operations:
- Binary operators:
and
,or
- Boolean negation (unary operator):
!
,not
- Binary operators:
- Comparisons and equality:
- Comparators:
>
,<
,>=
,<=
(gt
,lt
,ge
,le
) - Equality operators:
==
,!=
(eq
,ne
)
- Comparators:
- Conditional operators:
- If-then:
(if) ? (then)
- If-then-else:
(if) ? (then) : (else)
- Default:
(value) ?: (defaultvalue)
- If-then:
表达式预处理
最后要讲到的是表达式预处理,它被定义在_之间:
- #{selection.__${sel.code}__}
一些基本属性
让我们看一组最基本的标准方言属性,以th:text开头,替换标签中的文字内容(这里再次强调THymeleaf的原型支持能力)。
- <p th:text="#{msg.welcome}">Welcome everyone!</p>
th:each将循环array或list中的元素并重复打印一组标签。
- <li th:each="book : ${books}" th:text="${book.title}">En las Orillas del Sar</li>
最后,Thymeleaf有很多th属性来定义XHTML或者HTML5属性,这些属性只是执行表达式并把值设置成HTML的属性值:
- <form th:action="@{/createOrder}">
- <input type="button" th:value="#{form.submit}" />
- <a th:href="@{/admin/users}">