Thymeleaf模板引擎、语法

150 阅读1分钟

pom坐标

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

效果测试

resources - templates 目录下创建网页文件,必须以.html结尾

image.png

编写接口

/**
 * @author tian
 * 在templates目录下的所有页面,只能通过Controller来跳转
 * 需要模板引擎的支持 themleaf依赖
 */
@Controller
public class IndexController {

    @RequestMapping("/test")
    public String test(){
        return "test";
    }
}

原理解析

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
    private Charset encoding;
    private boolean cache;
    .....................

小结

如果需要使用thymeleaf,只需要导入对应的依赖就可以了!将html页面放在resources - templates 目录下

Thymeleaf应用

Thymeleaf 通过在 html 标签中,增加额外属性来达到“模板+数据”的展示方式,示例代码如下。 所有的html元素都可以被Thymeleaf替换接管 th: 元素名

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--所有的html元素都可以被Thymeleaf替换接管   th: 元素名-->
<div th:text="${msg}"></div>
</body>
</html>

接口代码

/**
 * @author tian
 * 在templates目录下的所有页面,只能通过Controller来跳转
 * 需要模板引擎的支持 themleaf依赖
 */
@Controller
public class IndexController {

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

效果

image.png

语法

转义/不转义

接口

@RequestMapping("/test")
public String test(Model model){
    model.addAttribute("msg","<h1>hello,springBoot</h1>");
    return "test";
}

模板页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--所有的html元素都可以被Thymeleaf替换接管   th: 元素名-->
<div th:text="${msg}"></div>
<div th:utext="${msg}"></div>
</body>
</html>

效果

image.png

数组遍历

接口代码

@Controller
public class IndexController {

    @RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("users", Arrays.asList("zhang","su","liu"));
        return "test";
    }
}

模板页面取值

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--所有的html元素都可以被Thymeleaf替换接管   th: 元素名-->
<!--集合遍历-->
<h3 th:each="user:${users}" th:text="${user}"></h3>
</body>
</html>

效果

image.png