(7)thymeleaf的使用

引入thymeleaf:

在pom.xml中引入就可以了:

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

thymeleaf的使用

HTML文件放在templates文件夹下就可以了。

在controller中:

//查出一些数据在界面中显示
    @RequestMapping("/success")

    public String success(Map<String,Object>map){

        //在类路径下的templates/success.html

        map.put("hello","<h1>你好</h1>");

        map.put("users", Arrays.asList("zhangsh","jiangyi"));

        return "success";

    }

在html中获得数据:

1,先导入thymeleaf的命名空间(不导入也可以,就是没有提示,所以为了方便还是导入吧)

2.使用:

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

 

(7)thymeleaf的使用

(7)thymeleaf的使用

(7)thymeleaf的使用

(7)thymeleaf的使用

th:text:是可以指定内容的,即使之前HTML中有内容,也会被这个内容覆盖。

包括:th:id,th:class,也是同理,也是覆盖原来HTML中的内容。

<h1>成功</h1>
<!--将div里面的文本内容设置为我们指定的值-->

<div id="hello" th:id="hello2" th:text="${hello}">

这是显示欢迎信息

</div>

<div th:text="${hello}"></div>

<div th:utext="${hello}"></div>

<!--每次遍历都会生成当前这个标签3个h4-->

<h4 th:each="user:${users}" th:text="${user}"></h4>

<hr/>

<h4>

    <span th:each="user:${users}">[[${user}]]</span>

</h4>

[[ ]]等价于th:text

[{ }]等价于 th:utext

路径的写法

@{ }语法来引入路径的好处:

以后如果我们需要更改项目名称:

比如我们在配置文件中添加了:

server.contex-path:/crud,

那么用@{}会自动加入/crud

注意:以后所有的路劲都要写成这个形式,要不然有的时候会有404错误,特别是静态资源。用/webjars的时候。

<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">

根据这个来写:

(7)thymeleaf的使用