Spring Boot笔记六:Thymeleaf介绍

目录

什么是thymeleaf?

thymeleaf是一个模板引擎,是用来在Spring Boot中代替JSP的

  1. 引用thymeleaf

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
  2. 控制thymeleaf的版本号(thymelaf3以上的话,layout必须2以上才支持)

    <properties>
        <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
    </properties>

创建最简单的thymeleaf

thymeleaf默认的路径是classpath://templates,必须是这个路径才能识别

我们在templates文件夹下面新建一个Vae.html,然后在Controller里面写一个方法去调用这个html

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

点击运行,如图:

完美,我们已经新建了一个最简单的thymeleaf了

thymeleaf语法

可以去官网下载文档查看

  1. 写一个hello传到html,我的Controller改为这样
    @RequestMapping("/Vae")
    public String thymeleafTest(Map<String,Object> map){
        map.put("hello","你好");
        return "Vae";
    }

前端的html需要做两个地方

  1. 引入thymeleaf的声明,这样写thymeleaf就会有提示
<html xmlns:th="http://www.thymeleaf.org">
  1. 用thymeleaf
<div th:text="${hello}">欢迎</div>

写完之后,整个前端html就是这样

<html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>thymeleaf许嵩</h1>

<div th:text="${hello}">欢迎</div>
</body>
</html>

重启,再来访问,如图:

非常好,写th:text后面的${},让我想起来了JSP里面的EL。可以发现我

里面用了thymeleaf,将会得到“你好”二字,如果我们将这个html拷贝到项目外面会,显示的就是欢迎了,这表明了一件事

含有thymeleaf语法的html文件只有经过thymeleaf模板解析之后生效,项目之外就变成一个普通的HTML了

  1. th可以替换任意的HTML元素
<div id="${hello}" class="${hello}" th:text="${hello}"></div>
  1. thymeleaf表达式
${}:这个我们已经用过了,就是取值的
*{}:这个是代指${},例如Person类有name属性,${Person.name}=*{name}
#{}:获取国际化内容
@{}:定义url的,例如 @{https://localhost:8080(id=${Id})}
~{}:片段引用表达式

猜你喜欢

转载自www.cnblogs.com/yunquan/p/10344449.html
今日推荐