Spring Boot 集成 Thymeleaf

2022-11-20  本文已影响0人  Tinyspot

1. Thymeleaf

1.1 模板引擎

1.2 特点

示例:<span th:text="${userName}">hello</span>
从服务器读取到数据时,用 userName 覆盖 hello;若未读取,直接使用 hello

2. Thymeleaf语法

3. 实战

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
</dependency>
spring:
  thymeleaf:
    cache: false # 开发时关闭缓存,可查看实时页面
    mode: LEGACYHTML5 # 非严格的html 格式, nekohtml提供的
    encoding: UTF-8
    servlet:
      content-type: text/html

index.html 文件
声明名称空间 xmlns:th="http://www.thymeleaf.org

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf Demo</title>
</head>
<body>
    <span th:text="${user.name}">other</span>
</body>
</html>

测试

@Controller // 返回 html页面
public class IndexController {

    @GetMapping(value = {"", "index"})
    public String index(Model model) {
        User user = new User("Tinyspot", 20);
        model.addAttribute("user", user);

        // Thymeleaf 模板自动添加后缀 .html
        return "index";
    }
}
上一篇 下一篇

猜你喜欢

热点阅读