一、簡介
Thymeleaf是一個XML / XHTML / HTML5模板引擎,適用於Web和獨立環境。
Thymeleaf的主要目標是提供一種優雅而又高度可維護的創建模板的方式。為了實現這個目標,Thymeleaf在自然模板中完全嵌入了HTML,並添加了自定義屬性以轉換靜態模板到模型。
二、基本語法
Thymeleaf使用「屬性替換」語法。
<div th:text="${title}">This will be replaced with the value of the title variable</div>
使用這個基本語法,可以通過設置th:*屬性來操作元素的屬性值:
<p th:text="${book.title}">The Book Title</p>
Thymeleaf的注釋語法和HTML相同。
<!-- This is an HTML comment -->
<!-- ! This is a Thymeleaf comment ! -->
三、變數
Thymeleaf應用程序的上下文變數可以在表達式中使用(前綴「$」):${…}和「selection」表達式。
在Thymeleaf中,可以使用th:object設置一個形式上的「當前對象」,使得在之後的處理中可以使用相對屬性選擇器:
<form th:object="${formBean}">
<input th:field="*{propertyName}" />
</form>
四、迭代
Thymeleaf提供了直接在模板中進行迭代和分頁的功能。
以下是一個迭代對象列表並顯示每個對象屬性的例子:
<ul>
<li th:each="user : ${users}">
<span th:text="${user.name}">User Name</span> : <span th:text="${user.age}">User Age</span>
</li>
</ul>
五、條件語句
Thymeleaf提供了常見條件表達式的相關命令。
以下是一個例子,用於顯示一個變數的值是否為空:
<p th:if="${variable != null}">Value :<span th:text="${variable}"></span></p>
六、模板組成
Thymeleaf提供了使用片段應用程序的方便正確實現模板組合的功能。
以下是一個繼承模板的例子:
<html>
<head th:fragment="common-header">
<title>The title</title>
</head>
<body>
<header><h1>The Header</h1></header>
<nav>... Navigation panel ...</nav>
<div th:fragment="main">
... Main content ...原創文章,作者:TPYDU,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/334668.html