SpringBoot有关模板引擎

模板引擎
将模板和数据进行整合,数据解析填充到指定位置,最终生成一个想要的内容
例如:JSP、Velocity、FreeMarker、Thymeleaf等
Thymeleaf是SpringBoot推荐使用的高级模板引擎
引入:

		<!--引入Thymeleaf模板引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

若想改thymeleaf的版本号,在properties中配置
其中layout需要2以上版本
Thymeleaf的使用及语法
在这里插入图片描述
在这里插入图片描述

		<!-- Thymeleaf 3 -->
		<org.thymeleaf-version>3.0.11.RELEASE</org.thymeleaf-version>
		<org.thymeleaf.extras.springsecurity4-version>3.0.2.RELEASE</org.thymeleaf.extras.springsecurity4-version>
		<nz.net.ultraq.thymeleaflayout-version>2.3.0</nz.net.ultraq.thymeleaflayout-version>
		<thymeleaf-extras-java8time-version>3.0.1.RELEASE</thymeleaf-extras-java8time-version>

看一下底层源码,添加了一些解析器,视图解析器等,默认的配置在ThymeleafProperties中,Ctrl长按点进去查看源码

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";
    //只要我们把HTML页面放在classpath:/templates路径下,Thymeleaf就会自动渲染了
    private String mode = "HTML";
    private Charset encoding;

Thymeleaf官方文档https://www.thymeleaf.org/documentation.html

Thymeleaf的使用

  • 引入Thymeleaf的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">

使用Thymeleaf语法

  • th:任意html属性:来替换原生html的属性值
<div th:text="${hello}">欢迎信息</div>
将div中的text设置为hello请求

Controller中:

    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "Hello World";
    }
    @RequestMapping("/success")
    public String success(Map<String,Object> map){
        map.put("hello","你好");
        return "success";
    }

执行结果:

在这里插入图片描述Thymeleaf的语法规则

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>成功!</h1>
    <div th:text="${hello}">欢迎信息</div>
    <hr/>
<!--    th:each每次遍历都会生成这个标签-->
<h2 th:text="${user}" th:each="user:${users}"></h2>
    <hr/>
    <h4>
        <!--注意行内写法:[[]]和[()]其中[[]]就是相当于th:text;[()]相当于th:utext-->
        <span th:each="user:${users}"> [[${user}]] </span>
    </h4>
</body>
</html>

调试多次报错,最后发现是最后的注释会报错,可能是里面的标识符导致的
调试结果:
在这里插入图片描述

发布了73 篇原创文章 · 获赞 20 · 访问量 4446

猜你喜欢

转载自blog.csdn.net/lzl980111/article/details/103973160