Thymeleaf 是一个用于Web和独立环境的现代服务器端Java模板引擎,它允许开发者将逻辑注入到模板文件中,从而实现动态内容的生成。Thymeleaf 与 Spring 框架集成良好,常用于Spring MVC项目中。
Thymeleaf 的核心概念包括:
Thymeleaf 表达式主要分为以下几种:
${...}
,用于获取变量值。*{...}
,通常用于表单对象。#{...}
,用于国际化消息。@{...}
,用于生成URL。~{...}
,用于模板的片段引用。以下是一个简单的Thymeleaf模板示例:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Example</title>
</head>
<body>
<h1 th:text="${title}">Default Title</h1>
<p th:text="${message}">Default Message</p>
<ul>
<li th:each="item : ${items}" th:text="${item}"></li>
</ul>
<form action="#" th:action="@{/submit}" method="post">
<input type="text" name="name" th:value="${user.name}" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
在这个例子中,${title}
和 ${message}
是变量表达式,用于显示上下文中的数据。th:each
是迭代表达式,用于遍历列表。th:action
是链接表达式,用于生成表单提交的URL。
问题:Thymeleaf 模板无法正确渲染数据。
原因:
解决方法:
例如,在Spring MVC控制器中:
@Controller
public class MyController {
@GetMapping("/example")
public String example(Model model) {
model.addAttribute("title", "Welcome Page");
model.addAttribute("message", "Hello, Thymeleaf!");
model.addAttribute("items", Arrays.asList("Item 1", "Item 2", "Item 3"));
return "example"; // 对应example.html模板文件
}
}
确保example.html
文件位于正确的模板目录中,如src/main/resources/templates/example.html
。
通过以上步骤,可以解决大多数Thymeleaf模板渲染问题。如果问题仍然存在,建议查看服务器日志以获取更多调试信息。
领取专属 10元无门槛券
手把手带您无忧上云