📅  最后修改于: 2023-12-03 14:47:32.852000             🧑  作者: Mango
Thymeleaf是一个Java模板引擎。它具有简单而强大的语法,易于阅读和编写。Spring Boot支持使用Thymeleaf作为Spring MVC视图。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
@EnableWebMvc
@Configuration
public class ThymeleafConfig {
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(htmlTemplateResolver());
return templateEngine;
}
@Bean
public SpringResourceTemplateResolver htmlTemplateResolver(){
SpringResourceTemplateResolver emailTemplateResolver = new SpringResourceTemplateResolver();
emailTemplateResolver.setPrefix("classpath:/templates/");
emailTemplateResolver.setSuffix(".html");
emailTemplateResolver.setTemplateMode(TemplateMode.HTML);
return emailTemplateResolver;
}
@Bean
public ViewResolver viewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
return viewResolver;
}
}
在src/main/resources/templates
目录下创建一个index.html
文件。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Boot Thymeleaf Demo</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
@Controller
public class HomeController {
@RequestMapping("/")
public String home(Model model) {
model.addAttribute("message", "Hello, World!");
return "index";
}
}
运行应用程序并访问http://localhost:8080/
,您应该能够看到Hello, World!
字样。
Thymeleaf使用#{}和${}
语法表示表达式语言(EL)。
${}
可以用于从模型中取值
<h1 th:text="${message}"></h1>
#{}可以用于读取国际化消息
<h1 th:text="#{welcome.message}"></h1>
Thymeleaf提供了各种条件语句来根据表达式的值在页面上呈现不同的结果。
<div th:if="${flag}">This content will be displayed if flag is true.</div>
<div th:unless="${flag}">This content will be displayed if flag is false.</div>
Thymeleaf中可以使用三种循环:for-each、while和迭代器。
<ul>
<li th:each="fruit: ${fruits}" th:text="${fruit}"></li>
</ul>
Thymeleaf的布局功能可以大大简化页面的开发,减少重复的代码。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Layout example</title>
</head>
<body>
<div th:fragment="header">
<h1>My header</h1>
</div>
<div th:fragment="content">
<p>Page content goes here.</p>
</div>
<div th:fragment="footer">
<p>My footer © 2021</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
th:fragment="defaultFragment">
<head>
<meta charset="UTF-8" />
<title>Layout Example</title>
</head>
<body>
<div th:replace="fragments/header :: header"></div>
<div th:replace="${content}"></div>
<div th:replace="fragments/footer :: footer"></div>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
th:include="fragments/layout :: defaultFragment">
<head>
<title>Page Title</title>
</head>
<body>
<div th:replace="fragments/content :: content">
<p>This is the page content.</p>
</div>
</body>
</html>