Thymeleaf是一個模板引擎,可用於Web和獨立環境。它是一個開源的Java庫,可用於處理XML,HTML,JavaScript,CSS,甚至純文本。
一、基本語法
Thymeleaf模板引擎使用類似於HTML的語法,但具有特殊的標籤以及額外的屬於它自己的語法。
如下是Thymeleaf的基本語法:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello World</title>
</head>
<body>
<p th:text="${'Hello, ' + name}">沒有設置名字</p>
</body>
</html>
在上面的示例代碼中,我們使用th:text屬性告訴引擎輸出「Hello,名字」。
使用Thymeleaf的語法,你可以像使用正常的HTML標籤一樣使用它內置的屬性和標籤,例如:
<p th:if="user.isAdmin">只有管理員能看到</p>
<div th:switch="${user.role}">
<p th:case="'admin'">你是管理員</p>
<p th:case="'user'">你是普通用戶</p>
<p th:case="*">你是新用戶</p>
</div>
上述代碼中,我們使用了th:if和th:switch屬性來指示引擎條件邏輯。這些屬性的語法看起來很像Java。
二、模板布局
Thymeleaf允許使用一個獨立的布局文件作為模板,這個文件定義了整個站點的結構,每個頁面「擴展」它並覆蓋其中的模塊。
下面是一個示例代碼展示如何使用布局模板:
布局模板 – layout.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>My Site</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/home" th:href="@{/home}">Home</a></li>
<li><a href="/about" th:href="@{/about}">About</a></li>
<li><a href="/contact" th:href="@{/contact}">Contact</a></li>
</ul>
</nav>
</header>
<section>
<div th:replace="template :: content"></div>
</section>
<footer>
<p>All rights reserved!</p>
</footer>
</body>
</html>
模塊模板 – home.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:include="layout :: layout">
<head>
<title>Home</title>
</head>
<body>
<!-- Override the content section of the layout.html file -->
<div th:fragment="content">
<h1>Welcome to my site!</h1>
<p>This is the home page.</p>
</div>
</body>
</html>
在上述示例中,我們使用th:replace屬性告知引擎插入一個模板片段。我們還使用了th:fragment屬性,它定義了模板片段的名字。
三、迭代
當你使用Thymeleaf構建動態Web頁面時,你經常需要迭代集合,例如:
<ul>
<li th:each="item : ${items}">
<a th:href="@{/view/(id=${item.id})}">[[${item.name}]]</a>
</li>
</ul>
在上述代碼中,我們使用th:each屬性迭代items集合,使用item變數來引用當前迭代項。我們還使用了th:href屬性來定義鏈接URL,並在鏈接文本中使用了Thymeleaf表達式。
四、條件渲染
Thymeleaf提供了多種條件渲染方式。你可以使用th:if和th:unless屬性,條件渲染有點像if和unless語句。
如下是一個簡單的例子:
<p th:if="${user.isAdmin}">Admin</p>
<p th:unless="${user.isAdmin}">Not Admin</p>
在上述代碼中,我們使用了th:if和th:unless屬性,這些屬性提供了基於條件渲染的功能,如果滿足條件則渲染。
五、變數表達式
Thymeleaf支持多種變數表達式,例如:
${…}用於查詢表達式的值。
*{…}用於屬性值或類型的聲明。
${fns:xxx(…)}使用Thymeleaf標準函數庫執行表達式。
#{…}用於國際化文本顯示。
下面是一個使用變數表達式的示例:
<p>Price: <span th:text="${price}"></span></p>
<input type="text" th:field="*{username}">
<p th:text="${#dates.format(date, 'dd-MM-yyyy')}">29-10-2022</p>
<p th:text="#{user.welcome}">Hello, User!</p>
在上述代碼中,我們使用了變數表達式,例如th:text屬性,它被使用來引用 price 變數的內容,另外我們使用了th:field屬性來綁定到一個輸入元素,這裡我們使用了*{username}變數,並推斷出了它的類型,並根據它的類型生成了name屬性。我們還使用了#{}符號來提示引擎通過對指定鍵執行國際化來顯示文本。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/192733.html