thymeleaf模板引擎

thymeleaf 模块引擎类似于JSP的EL表达式

1.引入thymeleaf   

<!--pom.xml文件-->
<!-- 导入thymeleaf模板依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>


<!--可以用默认的版本也可以自己更改-->
<properties>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>

2.thymeleaf的使用&语法

  只要我们把HTML文件放在classpath:/templates;thymeleaf 会自动渲染

           

     1)场景:我们controller有数据需要在HTML展示

      a.      在controller层写数据例如:

        

       b.   在HTML引入    <html lang="zh" xmlns:th="http://www.thymeleaf.org">   thymeleaf的名称空间

          并在body里写入

        

       c.  启动 SpringBoot 访问/success

        

3.thymeleaf命名的规则   

  1)基本属性

  html有的属性,Thymeleaf基本都有,而常用的属性大概有七八个。其中th属性执行的优先级从1~8,数字越低优先级越高。

  一、th:text :设置当前元素的文本内容,相同功能的还有th:utext,两者的区别在于前者不会转义html标签,后者会。优先级不高:order=7

  二、th:value:设置当前元素的value值,类似修改指定属性的还有th:srcth:href。优先级不高:order=6

  三、th:each:遍历循环元素,和th:text或th:value一起使用。注意该属性修饰的标签位置,详细往后看。优先级很高:order=2

  四、th:if:条件判断,类似的还有th:unlessth:switchth:case。优先级较高:order=3

  五、th:insert:代码块引入,类似的还有th:replaceth:include,三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景。优先级最高:order=1

  六、th:fragment:定义代码块,方便被th:insert引用。优先级最低:order=8

  七、th:object:声明变量,一般和*{}一起配合使用,达到偷懒的效果。优先级一般:order=4

  八、th:attr:修改任意属性,实际开发中用的较少,因为有丰富的其他th属性帮忙,类似的还有th:attrappend,th:attrprepend。优先级一般:order=5

  2)表达式

   一、变量表达式${ }   

      例子:<th:utext="${user.name}"></p>

  二、选择表达式*{ }

    <div th:object="${session.user}">

    <p>name: <span th:text="*{name}"></span></p>
    <p>age: <span th:text="*{age}"></span></p>
    <p>habbit: <span th:text="*{habbit[0]}"></span></p>
    </div>

  三、URL链接表达式 @{ }

    <th:href="@{/main}">main</a>

   四、获取国际化内容 #{ }

  五、片段引用表达式 ~{ }

   简单测试一下:controller层

    

     HTML 页面:  其中[[]] 表示th:text   [()]表示th:utext

    

     查看页面

    


原文地址:https://www.cnblogs.com/lihui123/p/14156656.html