您好,登录后才能下订单哦!
Thymeleaf 是一个现代化的服务器端 Java 模板引擎,适用于 Web 和独立环境。它能够处理 HTML、XML、JavaScript、CSS 甚至纯文本。Thymeleaf 的主要目标是提供一种优雅且高度可维护的模板创建方式。本文将总结 Thymeleaf 的常用语法,帮助开发者快速上手和使用。
在 HTML 文件中使用 Thymeleaf 时,首先需要引入 Thymeleaf 的命名空间:
<html xmlns:th="http://www.thymeleaf.org">
Thymeleaf 提供了多种表达式语法,用于在模板中嵌入动态内容。
${...}
用于访问模型中的变量或属性。
<p th:text="${user.name}">User Name</p>
*{...}
用于选择当前对象中的属性。
<div th:object="${user}">
<p th:text="*{name}">User Name</p>
</div>
#{...}
用于国际化消息。
<p th:text="#{welcome.message}">Welcome Message</p>
@{...}
用于生成 URL。
<a th:href="@{/user/profile}">Profile</a>
~{...}
用于引用模板片段。
<div th:replace="~{fragments/header :: header}"></div>
th:text
用于设置元素的文本内容。
<p th:text="${user.name}">User Name</p>
th:utext
用于设置元素的文本内容,且不转义 HTML 标签。
<p th:utext="${user.bio}">User Bio</p>
th:if
和 th:unless
用于条件渲染。
<p th:if="${user.isAdmin}">Admin User</p>
<p th:unless="${user.isAdmin}">Regular User</p>
th:each
用于循环遍历集合。
<ul>
<li th:each="user : ${users}" th:text="${user.name}">User Name</li>
</ul>
th:object
用于指定当前对象。
<div th:object="${user}">
<p th:text="*{name}">User Name</p>
</div>
th:href
和 th:src
用于设置链接和资源路径。
<a th:href="@{/user/profile}">Profile</a>
<img th:src="@{/images/logo.png}" alt="Logo">
th:class
和 th:style
用于动态设置 CSS 类和样式。
<div th:class="${user.isActive} ? 'active' : 'inactive'">User Status</div>
<div th:style="'color:' + ${user.color}">User Color</div>
支持基本的算术操作符:+
, -
, *
, /
, %
。
<p th:text="${user.age + 5}">Age in 5 years</p>
支持比较操作符:>
, <
, >=
, <=
, ==
, !=
。
<p th:if="${user.age > 18}">Adult</p>
支持逻辑操作符:and
, or
, not
。
<p th:if="${user.isActive and user.age > 18}">Active Adult</p>
支持三元条件操作符:condition ? then : else
。
<p th:text="${user.isActive} ? 'Active' : 'Inactive'">User Status</p>
Thymeleaf 提供了一些内置的工具对象,方便在模板中使用。
#dates
用于处理日期和时间。
<p th:text="${#dates.format(user.birthDate, 'yyyy-MM-dd')}">Birth Date</p>
#strings
用于处理字符串。
<p th:text="${#strings.toUpperCase(user.name)}">User Name</p>
#lists
用于处理列表。
<p th:text="${#lists.size(users)}">Number of Users</p>
#maps
用于处理映射。
<p th:text="${#maps.get(user.preferences, 'theme')}">User Theme</p>
可以使用 th:replace
或 th:include
引用模板片段。
<div th:replace="~{fragments/header :: header}"></div>
可以使用 th:fragment
定义可重用的模板片段。
<!-- fragments/header.html -->
<header th:fragment="header">
<h1>Welcome to My Website</h1>
</header>
然后在其他模板中引用:
<div th:replace="~{fragments/header :: header}"></div>
Thymeleaf 是一个功能强大且灵活的模板引擎,适用于各种 Java Web 应用场景。通过掌握其常用语法和属性,开发者可以高效地创建和维护动态 Web 页面。本文总结了 Thymeleaf 的基本语法、常用属性、操作符、工具对象以及模板布局等内容,希望能够帮助读者快速上手 Thymeleaf。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。