因为博客系统的信息都是用thymeleaf调用的,所以必须要学会前端怎么写thymeleaf方言风格的代码,我进行了一下浅略的学习。

1.标准表达式语法

  • ${...}:变量表达式。

  • *{...}:选择表达式。

  • #{...}:消息(i18n)表达式。

  • @{...}:链接(URL)表达式。

  • ~{...}:片段表达式。

1.1.变量表达式

变量表达式是在上下文变量上执行的 OGNL 表达式,形如:${session.user.name}

例子如下:

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

<li th:each="book : ${books}">

这里${books}选择从上下文中调用 books 的变量,并将其计算为可在 th:each 循环中使用的可迭代变量。

1.2.选择表达式

选择表达式与变量表达式类似,只不过它们将在先前选择的对象上执行,而不是在整个上下文变量映射上执行。它们看起来像这样*{customer.name}

它们作用的对象由属性 th:object 指定,例子如下:

<div th:object="${book}">
  ...
  <span th:text="*{title}">...</span>
  ...
</div>

1.3.消息表达式

消息表达式(通常称为文本外化、国际化或 i18n)允许我们从外部源(.properties 文件)检索特定于区域设置的消息,通过键引用它们并(可选)应用一组参数。

例子如下:

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

1.4.链接表达式

链接表达式旨在构建 URL 并向其添加有用的上下文和会话信息。个人感觉就是href支持所有的GET方法的url类型,和访问本地资源路径的url

例子如下:

<a th:href="@{/order/list}">...</a>

<a th:href="@{/order/details(id=${orderId},type=${orderType})}">...</a>

<a th:href="@{../documents/report}">...</a>

<a th:href="@{~/contents/main}">...</a>

<a th:href="@{http://www.mycompany.com/main}">...</a>

1.5.片段表达式

片段表达式是一种表示标记片段并在模板中移动它们的简单方法。(其实没看的太懂)

例子如下:

<div th:insert="~{commons :: main}">...</div>

<div th:with="frag=~{footer :: #main/text()}">
  <p th:insert="${frag}">
</div>

1.6.文本和操作

  • 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) 

1.7.表达式预处理

有一种叫做表达式预处理的东西,在__之间指定,如下所示:

#{selection.__${sel.code}__}

2.基础语法

参考资料:

史上最详 Thymeleaf 使用教程-CSDN博客

5 分钟标准方言入门 - Thymeleaf --- Getting started with the Standard dialects in 5 minutes - Thymeleaf