Thymeleaf 是一个流行的 Java 模板引擎,用于 Web 和独立环境,能够处理 HTML、XML、JavaScript、CSS 甚至纯文本。当涉及到在 Thymeleaf 中结合 JavaScript 进行页面跳转时,有几种常见的方法:
${...}
、*{...}
、@{...}
等)来在模板中嵌入动态内容。window.location.href
、window.location.replace
等。假设我们有一个按钮,点击后根据某个条件跳转到不同的页面:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf JS 跳转示例</title>
</head>
<body>
<button onclick="redirectBasedOnCondition()">点击跳转</button>
<script>
function redirectBasedOnCondition() {
var condition = true; // 这里可以替换为实际的条件判断逻辑
if (condition) {
window.location.href = "/success.html";
} else {
window.location.href = "/failure.html";
}
}
</script>
</body>
</html>
假设我们需要在跳转时传递一个参数 id
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf JS 跳转示例</title>
</head>
<body>
<button onclick="redirectWithParam()">点击跳转</button>
<script>
function redirectWithParam() {
var id = 123; // 这里可以替换为实际的参数值
window.location.href = "/details.html?id=" + id;
}
</script>
</body>
</html>
在 details.html
中,Thymeleaf 可以接收并处理这个参数:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>详情页面</title>
</head>
<body>
<p>详情 ID: <span th:text="${param.id}"></span></p>
</body>
</html>
console.log
调试。encodeURIComponent
对参数进行编码。${param.id}
接收参数。通过以上方法,可以在 Thymeleaf 中结合 JavaScript 实现灵活的页面跳转逻辑。
领取专属 10元无门槛券
手把手带您无忧上云