thymeleaf3.0学习

一、th属性

1、th:text:设置当前元素的文本内容,类似修改制定属性的还有th:utext,区别在于后者不会转义html标签
2、th:value:设置当前元素的value值,类似的还有th:src、th:href
3、th:each:循环遍历元素;th:each="item : ${collection}",然后使用th:text="${item}"赋值表达式给标签赋值。
4、th:if:条件判断,类似th:unless,th:switch,th:case。判断不为空才显示th:if="${not #strings.isEmpty(result)}"
5、th:insert:代码块引入,类似的有th:replace,th:include;th:insert插入到当前标签下,th:insert:保留自己的主标签,保留th:fragment的主标签。tth:replace:不要自己的主标签,保留th:fragment的主标签。th:include:不要自己的主标签,保留th:fragment的主标签。(官方3.0后不推荐使用)。
6、th:fragment:定义代码块
7、th:object:声明变量,一般和*{}一起配合使用

二、注意

1、声明名称空间:`xmlns:th="http://www.thymeleaf.org`
2、设置文本内容th:text,设置input的值th:value,循环输出th:each,条件判断th:if,插入代码块th:insert,定义代码块th:fragment,声明变量th:object
3、th:each放在需要被循环的标签上。
4、变量表达式中提供了很多的内置方法,该内置方法是用#开头,请不要与#{}消息表达式弄混。
5、th:insert、th:replace、th:include三种插入代码块的效果相似,但区别很大。

三、标准表达式语法

 1、${...}:变量表达式
    常见的内置对象
    ①ctx:上下文对象 ②vars:上下文变量 ③locale:上下文的语言对象 ④request:获取HttpServletRequest对象
    ④response:获取HttpServletResponse对象 ⑤session:获取HttpSession对象 ⑥获取ServletContext对象
    常用的内置方法
    ①strings:字符串格式化方法,如equals、equalsIgnoreCase、length、trim、toUpperCase、toLowerCase、
    indexOf、substring、replace、startWith、endsWith、contains、containsIgnoreCase等
    ②numbers:formatDecimal
    ③bools:isTrue、isFalse
    ④arrays:toArray,length,isEmpty,contains,containsAll等
    ⑤list、sets:toList,size,isEmpty,contains,containsAll,sort等
    ⑥maps:size,isEmpty,containsKey,containsValue等
    ⑦dates:format,year,month,hour,createNow等

2、@{...}:链接表达式
    可以动态获取项目路径

3、#{...}:消息表达式

4、~{...}:代码块表达式
    支持两种语法结构
    推荐:~{templatename::fragmentname}
    支持:~{templatename::#id}

5、*{...}:选择变量表达式
    多用于和th:object结合使用

四、thymeleaf在SpringBoot应用

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
  <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
  <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
  <dependency> 
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
</dependencies>

    有时候可能需要引入依赖
<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.15</version>
</dependency>

    application.properties加入设置:
    spring.thymeleaf.cache=false
    spring.thymeleaf.mode=LEGACYHTML5

猜你喜欢

转载自www.cnblogs.com/hucheng1997/p/11025319.html