您的位置:首页 > 其它

5分钟了解Thymeleaf的标准方言(Standard dialects)

2014-10-27 21:13 253 查看
这篇指南将介绍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}
它们将以HTML标签的一个属性来表示:

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


选择(星号)表达式

选择表达式很像变量表达式,不过它们用一个预先选择的对象来代替上下文变量容器(map)来执行,如下:
*{customer.name}
被指定的object由th:object属性定义:
<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}
URLs还可以设置参数:
@{/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 operations:

String concatenation:
+

Literal substitutions:
|The name is ${name}|


Arithmetic operations:

Binary operators:
+
,
-
,
*
,
/
,
%

Minus sign (unary operator):
-


Boolean operations:

Binary operators:
and
,
or

Boolean negation (unary operator):
!
,
not


Comparisons and equality:

Comparators:
>
,
<
,
>=
,
<=
(
gt
,
lt
,
ge
,
le
)
Equality operators:
==
,
!=
(
eq
,
ne
)

Conditional operators:

If-then:
(if) ? (then)

If-then-else:
(if) ? (then) : (else)

Default:
(value) ?: (defaultvalue)


表达式预处理

最后要讲到的是表达式预处理,它被定义在_之间:
#{selection.__${sel.code}__}
我们看到的变量表达式${sel.code}将先被执行,加入结果是"ALL",那么_之间的值"ALL"将被看做表达式的一部分被执行,在这里会变成selection.ALL。

一些基本属性

让我们看一组最基本的标准方言属性,以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}">


想了解更多?

请参考更详尽文档。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: