thymeleaf基本語法

thymeleaf標準表達式語法

  • $ {…} :變量表達式。
  • *{…} :選擇表達式。
  • #{…} :消息(i18n)表達式。
  • @ {…} :鏈接(URL)表達式。
  • ~ {…} :分段表達式。
  1. 變量的表達式
  • 官網解釋:

Variable expressions are OGNL expressions –or Spring EL if you’re integrating Thymeleaf with Spring– executed on the context variables — also called model attributes in Spring jargon. They look like this:

  • 語法
${session.user.name}
  • 用法
<span th:text="${book.author.name}">

等效於

((Book)context.getVariable("book")).getAuthor().getName()

實際例子
在這裏插入圖片描述

  1. 選擇表達式
  • 官網解釋:

Selection expressions are just like variable expressions, except they will be executed on a previously selected object instead of the whole context variables map. They look like this:

  • 語法
*{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());
}

實際例子
在這裏插入圖片描述

  1. 消息表達式
  • 官網解釋:

Message expressions (often called text externalization, internationalization or i18n) allows us to retrieve locale-specific messages from external sources (.properties files), referencing them by a key and (optionally) applying a set of parameters.

即:
表達式(通常稱爲消息 文字外化 , 國際化 或 i18n )允許我們從外部來源(檢索特定於本地語言環境的消息 . properties 文件),引用他們的一個關鍵和(可選)應用一組參數。

  • 語法
#{main.title}
#{message.entrycreated(${entryId})}
  • 用法
<table>
  ...
  <th th:text="#{header.address.city}">...</th>
  <th th:text="#{header.address.country}">...</th>
  ...
</table>

實際中的應用
在這裏插入圖片描述

  1. 鏈接(URL)表達式
  • 官網解釋:

Message expressions (often called text externalization, internationalization or i18n) allows us to retrieve locale-specific messages from external sources (.properties files), referencing them by a key and (optionally) applying a set of parameters.

即:
鏈接表達式是用來構建url並添加有用的上下文和會話信息(通常被稱爲過程 URL重寫 )。

所以對於一個web應用程序的部署 / myapp 您的web服務器的一個表達式,如:。

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

或者

<a href="/myapp/order/list">...</a>

還可以這樣

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

相對地址,在這種情況下,沒有應用程序上下文將前綴到URL:

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

於http協議相關(就像絕對url,但瀏覽器將使用相同的HTTP或HTTPS協議用於頁面顯示):

<a th:href="@{//static.mycompany.com/res/initial}">...</a>
  1. 分段表達式
  • 官網解釋:

Fragment expressions are an easy way to represent fragments of markup and move them around templates. Thanks to these expressions, fragments can be replicated, passed to other templates as arguments, and so on.

即:
片段表達式是一個簡單的方法來表示標記的片段和移動模板。 由於這些表達式,碎片可以被複制,作爲參數傳遞給其他模板,等等。

最常見的使用是片段插入使用 th:插入 或 th:替換 :

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

但他們可以在任何地方使用,就像任何其他變量:

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

實際中應用
在這裏插入圖片描述
相當於在下面的頁面中應用上面那段html

發佈了101 篇原創文章 · 獲贊 37 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章