首先在spring boot
项目依赖spring-boot-starter-thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 添加上述依赖Spring会自动注入
org.thymeleaf.spring5.SpringTemplateEngine
类
package com.meng.thymeleaf.web;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
@RestController
@AllArgsConstructor
@Slf4j
public class IndexController {
private TemplateEngine templateEngine;
@GetMapping(value = "", produces = MediaType.TEXT_HTML_VALUE)
public String index(Model model) {
model.addAttribute("title", "thymeleaf");
model.addAttribute("name", "Hello Thymeleaf");
Context context = new Context();
context.setVariables(model.asMap());
String result = templateEngine.process("index", context);
log.info("{}", result);
return result;
}
}
Context
为上下文- 静态化之后我们可以使用放入缓存中
输出内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>thymeleaf</title>
</head>
<body>
<h1>Hello Thymeleaf</h1>
</body>
</html>
模板文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title th:text="${title}">Title</title>
</head>
<body>
<h1 th:text="${name}"></h1>
</body>
</html>