SpringBoot--->Thymeleaf模板引擎

1、导入依赖

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>

只要导入对应的依赖,

2、练习使用Thymeleaf

1、在对应HTML页面导入相关依赖

<html lang="en" xmlns:th="http://www.thymeleaf.org">

对应HTML页面需要取值,使用  th:***="${+++}" 获取

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--/*@thymesVar id="msg" type="com.xian.controller.HelloController"*/-->
<div th:text="${msg}"></div>
</body>
</html>

2、在对应controller里跳转

@Controller
public class HelloController {
    @RequestMapping("/test")
    public String test(Model model) {
        model.addAttribute("msg","hello,springboot");
        return "test";
    }
}

3、练习使用数据填充

<!--/*@thymesVar id="msg" type="com.xian.controller.HelloController"*/-->
<div th:text="${msg}"></div>
<!--转义字符-->
<div th:utext="${msg}"></div>
<hr>
<!--/*@thymesVar id="users" type="com.xian.controller.HelloController"*/-->
<h3 th:each="user:${users}">[[ ${user} ]]</h3>

<!--推荐使用第二种方法,做到前后端分离,把数据写在前端页面里,不推荐-->
<h3 th:each="user:${users}" th:text="${user}"></h3>

2、对应的controller

public class HelloController {
    @RequestMapping("/test")
    public String test(Model model) {
        model.addAttribute("msg","<h1>hello,springboot</h1>");
        model.addAttribute("users", Arrays.asList("xian","Spring"));
        return "test";
    }
}

 文字过多,需要时及时翻看官方文档

Thymeleaf 官网:https://www.thymeleaf.org/

Thymeleaf 在Github 的主页:https://github.com/thymeleaf/thymeleaf

Spring官方文档:找到我们对应的版本

https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter

原文地址:https://www.cnblogs.com/springxian/p/14237397.html