Thymeleaf是一种基于Java的模板引擎,用于Web应用程序的视图层的开发。它的语法类似于HTML,但同时也具有许多内置功能,如表达式、条件语句和迭代器等。
Thymeleaf是在服务端渲染的。
变量表达式
变量表达式是Thymeleaf的基本语法,它允许你在模板中使用Java对象和变量。以下是一些示例:
html
<!-- 直接引用变量 -->
<p th:text="${name}"></p>
<!-- 调用对象的方法 -->
<p th:text="${user.getName()}"></p>
<!-- 访问对象的属性 -->
<p th:text="${user.age}"></p>
<!-- 使用默认值 -->
<p th:text="${name} ?: 'default value'"></p>
<!-- 使用三元运算符 -->
<p th:text="${user.isAdmin() ? 'Admin' : 'User'}"></p>
迭代器
迭代器允许你在模板中迭代集合或数组。以下是一些示例:
html
<!-- 迭代集合 -->
<ul>
<li th:each="item : ${items}" th:text="${item}"></li>
</ul>
<!-- 迭代数组 -->
<ul>
<li th:each="item : ${#arrays.asList(array)}" th:text="${item}"></li>
</ul>
<!-- 迭代数字范围 -->
<ul>
<li th:each="i : ${#numbers.sequence(1, 5)}" th:text="${i}"></li>
</ul>
条件语句
条件语句允许你在模板中根据条件显示不同的内容。以下是一些示例:
html
<!-- if语句 -->
<p th:if="${isAdmin}">Welcome, Admin!</p>
<p th:unless="${isAdmin}">Welcome, User!</p>
<!-- switch语句 -->
<div th:switch="${dayOfWeek}">
<p th:case="'MONDAY'">Monday</p>
<p th:case="'TUESDAY'">Tuesday</p>
<p th:case="'WEDNESDAY'">Wednesday</p>
<p th:case="'THURSDAY'">Thursday</p>
<p th:case="'FRIDAY'">Friday</p>
<p th:case="'SATURDAY'">Saturday</p>
<p th:case="'SUNDAY'">Sunday</p>
<p th:case="*">Invalid Day</p>
</div>
模板片段
模板片段允许你将可重用的代码块提取为片段,并在模板中重复使用它们。以下是一些示例:
html
<!-- 引用片段 -->
<div th:insert="~{fragments/header :: header}"></div>
<!-- 定义片段 -->
<div th:fragment="header">
<h1>Header</h1>
<p>Some text</p>
</div>
属性操作
属性操作允许你在模板中操作HTML元素的属性,如添加、删除、更新或切换属性的值。以下是一些示例:
html
<!-- 添加属性 -->
<img th:attr="src=@{/images/logo.png}" />
<!-- 删除属性 -->
<a th:remove="href">Link</a>
<!-- 更新属性 -->
<input th:value="${name}" th:attr="placeholder=#{name.placeholder}" />
<!-- 切换class属性 -->
<div th:classappend="${active ? 'active' : 'inactive'}"></div>
URL和表单处理
Thymeleaf提供了一些方便的方式来处理URL和表单。以下是一些示例:
html
<!-- URL处理 -->
<a th:href="@{/user/{id}/edit(id=${user.id})}">Edit User</a>
<!-- 表单处理 -->
<form th:action="@{/user/save}" th:object="${user}" method="post">
<input type="text" th:field="*{name}" />
<input type="text" th:field="*{age}" />
<button type="submit">Save</button>
</form>
国际化
Thymeleaf具有内置的国际化支持,允许你在模板中轻松处理多语言。以下是一些示例:
html
<!-- 显示本地化消息 -->
<p th:text="#{hello}"></p>
<!-- 显示带参数的本地化消息 -->
<p th:text="#{hello.name(${user.name})}"></p>
<!-- 显示当前语言 -->
<p th:text="#{language}"></p>
<!-- 切换语言 -->
<a th:href="@{/lang/fr}" th:text="#{language}"></a>
片段缓存
片段缓存允许你将部分页面缓存起来,以提高性能和响应速度。以下是一些示例:
html
<!-- 定义片段缓存 -->
<div th:fragment="header" th:cacheable="true">
<h1>Header</h1>
<p>Some text</p>
</div>
<!-- 使用片段缓存 -->
<div th:replace="~{fragments/header :: header}"></div>
总结
以上是Thymeleaf的常见用法,包括变量表达式、迭代器、条件语句、模板片段、属性操作、URL和表单处理、国际化以及片段缓存。Thymeleaf的强大功能和灵活的语法使其成为开发Web应用程序视图层的首选模板引擎之一。