Spring Boot thymleaf的使用

1. 首先导入themleaf的头文件

导入thymeleaf依赖

<!--thymeleaf模板-->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

2.themleaf的使用

1.导入头文件之后,在controller中存入数据,即可在html页面中取出来

 @RequestMapping("/in")
    public String index(Model model){
        model.addAttribute("msg","welcome to Spring Boot!");
        return "test";
    }

导入数据的时候,记得要添加model参数,进行存储数据

2.在html页面中取出数据

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

取出数据的时候,要加上th前缀, th:任意html属性;来替换原生属性的值

3.thymleaf常用属性:

一、th:text :设置当前元素的文本内容,相同功能的还有th:utext,两者的区别在于前者不会转义html标签,后者会。优先级不高:order=7
二、th:value:设置当前元素的value值,类似修改指定属性的还有th:src,th:href。优先级不高:order=6
三、th:each:遍历循环元素,和th:text或th:value一起使用。注意该属性修饰的标签位置,详细往后看。优先级很高:order=2
四、th:if:条件判断,类似的还有th:unless,th:switch,th:case。优先级较高:order=3
五、th:insert:代码块引入,类似的还有th:replace,th:include,三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景。优先级最高:order=1
六、th:fragment:定义代码块,方便被th:insert引用。优先级最低:order=8
七、th:object:声明变量,一般和*{}一起配合使用,达到偷懒的效果。优先级一般:order=4
八、th:attr:修改任意属性,实际开发中用的较少,因为有丰富的其他th属性帮忙,类似的还有th:attrappend,th:attrprepend。优先级一般:order=5

4.thymleaf演示

1. **th:text:**会转义 , 也就是会将文本中的h1转换为没有意义的h1

"<h1>hello , spring boot ! </h1>"

**th:utext:**不会转义,会将当做标签


2. th:each用于遍历

首先存入数据

 model.addAttribute("name", Arrays.asList("qianyi","kuangshen","java"));

存入之后,使用th:each取出数据,用user进行展示,再使用th:text取出user,展示在页面中。

<h1 th:each="user:${name}" th:text="${user}"></h1>

猜你喜欢

转载自blog.csdn.net/qq_45260619/article/details/105100345
今日推荐