Thymeleaf 是一个用于 Web 和独立环境的现代服务器端 Java 模板引擎。它允许开发者创建动态的 HTML、XML、JavaScript、CSS 甚至纯文本。Thymeleaf 的主要目标是提供一种优雅且高度可维护的模板编写方式,同时保持与现有模板引擎的兼容性。
Thymeleaf 和 JavaScript 可以很好地协同工作。Thymeleaf 主要负责服务器端的数据渲染,而 JavaScript 则负责客户端的交互和动态更新。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf and JavaScript Example</title>
</head>
<body>
<div th:text="${message}"></div>
<button onclick="updateMessage()">Update Message</button>
<script>
function updateMessage() {
// 使用 fetch API 从服务器获取新消息
fetch('/api/new-message')
.then(response => response.json())
.then(data => {
// 更新页面上的消息
document.querySelector('div').innerText = data.message;
});
}
</script>
</body>
</html>
在这个示例中,Thymeleaf 渲染初始的 message
,然后 JavaScript 函数 updateMessage
使用 fetch
API 从服务器获取新消息并更新页面上的内容。
通过理解 Thymeleaf 的基础概念、优势和类型,以及如何与 JavaScript 协同工作,开发者可以更有效地利用 Thymeleaf 构建动态 Web 应用程序。
领取专属 10元无门槛券
手把手带您无忧上云