系统梳理一下 thymeleaf 的用法

发布时间 2023-11-24 22:17:18作者: ahguo

Thymeleaf 是一个用于服务器端 Java 应用的模板引擎,它能够在 HTML/XML 模板中嵌入动态内容,提供了丰富的功能来简化模板和数据之间的集成。下面是 Thymeleaf 的一些主要用法:

表达式语法

Thymeleaf 使用类似于自然语言的表达式语法,可以在 HTML 中嵌入动态内容:

变量表达式

<span th:text="${user.name}">John Doe</span>

${user.name} 将会被替换为 user 对象中的 name 属性的值。

选择表达式

<a th:href="@{/home}" th:class="${isActive} ? 'active' : ''">Home</a>

@{/home} 用于生成链接,${isActive} 是一个布尔表达式,根据其值添加 active 类。

迭代器表达式

<tr th:each="user : ${users}">
    <td th:text="${user.name}">John Doe</td>
    <!-- ... -->
</tr>

${users} 是一个列表,th:each 用于遍历列表中的每个 user

属性操作

Thymeleaf 允许添加或删除 HTML 元素的属性:

设置属性

<input type="text" th:attr="placeholder=#{input.placeholder}">

th:attr 用于设置元素属性,#{input.placeholder} 是国际化消息。

片段和模板

Thymeleaf 支持片段化和模板重用:

引入片段

<div th:include="footer :: footerContent"></div>

th:include 用于包含其他模板中的片段。

条件逻辑

Thymeleaf 允许执行条件判断和循环:

条件判断

<div th:if="${user.isAdmin()}">Admin Section</div>

th:if 根据条件决定是否渲染该元素。

循环

<ul>
    <li th:each="fruit : ${fruits}" th:text="${fruit}">Apple</li>
</ul>

th:each 用于遍历集合并生成对应的元素。

表单处理

Thymeleaf 提供了表单处理支持:

表单绑定

<form th:object="${user}" th:action="@{/save}" method="post">
    <input type="text" th:field="*{name}" />
    <!-- ... -->
</form>

th:object 用于绑定对象到表单,th:field 绑定字段到输入元素。

国际化

Thymeleaf 支持国际化和多语言处理:

多语言消息

<p th:text="#{welcome.message}">Welcome</p>

#{welcome.message} 是从配置的消息源中获取的多语言消息。

其他功能

Thymeleaf 还提供了许多其他功能,比如模板布局、内联文本等功能。

总体来说,Thymeleaf 提供了强大的模板引擎功能,可以帮助开发者更加便捷地在服务器端 Java 应用中构建动态、可扩展的用户界面。