前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot前端 —— thymeleaf 简单理解

SpringBoot前端 —— thymeleaf 简单理解

作者头像
小锋学长生活大爆炸
发布2020-09-16 14:41:58
6.3K0
发布2020-09-16 14:41:58
举报

本文集各家之长,自学整理,若有错误,欢迎留言指出!!!


前置操作

1、创建工程 2、在pom.xml中加入thymeleaf

代码语言:javascript
复制
<!-- thymeleaf -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

3、修改项目为热部署,打开pom.xml,加入下面依赖,最后重启一次项目

代码语言:javascript
复制
<!-- spring-boot热部署 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

4、在resoures文件夹下分别创建templates(主要放html文件)和static(主要放css、js文件)文件夹 5、在application.yml配置thymeleaf(这样配置后,在代码中返回到那个页面就不用写过多的前缀和后缀了,达到简化效果)

代码语言:javascript
复制
spring:
  thymeleaf:
    cache: false  # 模板热部署、禁用 thymeleaf 缓存
    mode: HTML5
    suffix: .html
    prefix: classpath:/templates/
    encoding: UTF-8
    servlet:
      content-type: text/html
  mvc:
   static-path-pattern: /static/**  # 添加static文件夹下其他文件夹可访问

6、引入css文件(必须要在标签中加上rel属性)

代码语言:javascript
复制
<link th:href="@{/static/css/index.css}" type="text/css" rel="stylesheet">

7、引入js文件

代码语言:javascript
复制
<script type="text/javascript" th:src="@{/js/jquery.js}"></script>

Model、ModelMap、ModelAndView

  • Model   一般来说,可以用Model来接收各种类型的数据,如果使用来接收一组数据List,那么这个时候的Model实际上是ModelMap
  • ModelMap   主要用于传递控制方法处理数据到结果页面,也就是说我们把结果页面上需要的数据放到ModelMap对象中即可,他的作用类似于request对象的setAttribute方法的作用:用来在一个请求过程中传递处理的数据 ModelMap或者Model通过addAttribute方法向页面传递参数
  • ModelAndView   指模型和视图的集合,既包含 模型 又包含 视图

ModelModelMap 无需用户自己创建,而且需要return 返回指定的页面路径

代码语言:javascript
复制
public String listCategory2(Model model) {
    // 接收查询的信息
    List<Category> cs2= categoryService.list();
    // 封装了查询的数据
    model.addAttribute("test", cs2);
    //重要!!需要给出返回model跳转的路径
    return "listCategory2";
}

ModelAndView的实例是需要我们手动new的,这也是和ModelMap的一个区别。 而且,ModelAndView 可以自己寻址,只需要return 返回其对象即可。

代码语言:javascript
复制
public ModelAndView listCategory(){
  //创建一个模型视图对象
    ModelAndView mav = new ModelAndView();
    //获取到查询的数据
    List<Category> cs= categoryService.list();

    // //将数据放置到ModelAndView对象view中,第二个参数可以是任何java类型
    mav.addObject("cs", cs);
    // 放入jsp路径
    mav.setViewName("listCategory");
     //返回ModelAndView对象mav
    return mav;
}

注意点

一、 若要使用Thymeleaf语法,首先要声明名称空间: xmlns:th="http://www.thymeleaf.org"

二、 设置文本内容 th:text,设置input的值 th:value,循环输出 th:each,条件判断 th:if,插入代码块 th:insert,定义代码块 th:fragment,声明变量 th:object

三、 th:each 的用法需要格外注意,打个比方:如果你要循环一个div中的p标签,则th:each属性必须放在p标签上。若你将th:each属性放在div上,则循环的是将整个div

四、 变量表达式中提供了很多的内置方法,该内置方法是用#开头,请不要与#{}消息表达式弄混。

五、th:insertth:replaceth:include 三种插入代码块的效果相似,但区别很大。

示例概览:

代码语言:javascript
复制
<!DOCTYPE html>
<!--名称空间-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf 语法</title>
</head>
<body>
    <h2>ITDragon Thymeleaf 语法</h2>
    <!--th:text 设置当前元素的文本内容,常用,优先级不高-->
    <p th:text="${thText}" />
    <p th:utext="${thUText}" />

    <!--th:value 设置当前元素的value值,常用,优先级仅比th:text高-->
    <input type="text" th:value="${thValue}" />

    <!--th:each 遍历列表,常用,优先级很高,仅此于代码块的插入-->
    <!--th:each 修饰在div上,则div层重复出现,若只想p标签遍历,则修饰在p标签上-->
    <div th:each="message : ${thEach}"> <!-- 遍历整个div-p,不推荐-->
        <p th:text="${message}" />
    </div>
    <div> <!--只遍历p,推荐使用-->
        <p th:text="${message}" th:each="message : ${thEach}" />
    </div>

    <!--th:if 条件判断,类似的有th:switch,th:case,优先级仅次于th:each, 其中#strings是变量表达式的内置方法-->
    <p th:text="${thIf}" th:if="${not #strings.isEmpty(thIf)}"></p>

    <!--th:insert 把代码块插入当前div中,优先级最高,类似的有th:replace,th:include,~{} :代码块表达式 -->
    <div th:insert="~{grammar/common::thCommon}"></div>

    <!--th:object 声明变量,和*{} 一起使用-->
    <div th:object="${thObject}">
        <p>ID: <span th:text="*{id}" /></p><!--th:text="${thObject.id}"-->
        <p>TH: <span th:text="*{thName}" /></p><!--${thObject.thName}-->
        <p>DE: <span th:text="*{desc}" /></p><!--${thObject.desc}-->
    </div>

</body>
</html>
代码语言:javascript
复制
@RequestMapping("thymeleaf")
public String thymeleaf(ModelMap map) {
    map.put("thText", "th:text 设置文本内容 <b>加粗</b>");
    map.put("thUText", "th:utext 设置文本内容 <b>加粗</b>");
    map.put("thValue", "thValue 设置当前元素的value值");
    map.put("thEach", Arrays.asList("th:each", "遍历列表"));
    map.put("thIf", "msg is not null");
    map.put("thObject", new ThObject(1L, "th:object", "用来偷懒的th属性"));
    return "grammar/thymeleaf";
}

具体配置

基本内容样式

代码语言:javascript
复制
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="renderer" content="webkit">
        <title>首页</title>
        <link rel="shortcut icon" th:href="@{/favicon.ico}"/>
        <link th:href="@{/static/css/bootstrap.min.css}" rel="stylesheet"/>
        <link th:href="@{/static/css/font-awesome.min.css}" rel="stylesheet"/>
    </head>
    <body class="fixed-sidebar full-height-layout gray-bg" style="overflow:hidden">
        <div id="wrapper">
            <h1 th:text="${msg}"></h1>
        </div>
        <script th:src="@{/static/js/jquery.min.js}"></script>
        <script th:src="@{/static/js/bootstrap.min.js}"></script>
    </body>
</html>

表达式

(本部分内容绝大部分转载自:https://blog.csdn.net/xiaojin21cen/article/details/102935872)

简单表达式

  • ${...} 变量表达式:有丰富的内置方法,使其更强大,更方便
  • *{...} 选择变量表达式:使用频率最高,其功能也是非常的丰富。选择表达式首先使用th:object来绑定后台传来的的user对象,然后使用*来代表这个对象,后面{}中的值是此对象中的属性
  • #{...} 消息表达式:一般用于国际化的场景,结构:th:text="#{msg}"
  • @{...} 链接url表达式:静态资源的引用、form表单的请求,凡是链接都可以用@{...}
  • ~{...} 代码块表达式:~{模版名::片段名}、~{模版名::#id}

常用的内置对象

  • ctx :上下文对象。
  • vars :上下文变量。
  • locale:上下文的语言环境。
  • request:(仅在web上下文)的 HttpServletRequest 对象。
  • response:(仅在web上下文)的 HttpServletResponse 对象。
  • session:(仅在web上下文)的 HttpSession 对象。
  • servletContext:(仅在web上下文)的 ServletContext 对象
代码语言:javascript
复制
// java 代码将用户名放在session中
session.setAttribute("userinfo",username);
// Thymeleaf通过内置对象直接获取
th:text="${session.userinfo}"

常用的内置方法

  • strings:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等
  • numbers:数值格式化方法,常用的方法有:formatDecimal等
  • bools:布尔方法,常用的方法有:isTrue,isFalse等
  • arrays:数组方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等
  • lists,sets:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等
  • maps:对象方法,常用的方法有:size,isEmpty,containsKey,containsValue等
  • dates:日期方法,常用的方法有:format,year,month,hour,createNow等
代码语言:javascript
复制
<h3>#strings </h3>
<div th:if="${not #strings.isEmpty(itdragonStr)}" >
    <p>Old Str : <span th:text="${itdragonStr}"/></p>
    <p>toUpperCase : <span th:text="${#strings.toUpperCase(itdragonStr)}"/></p>
    <p>toLowerCase : <span th:text="${#strings.toLowerCase(itdragonStr)}"/></p>
    <p>equals : <span th:text="${#strings.equals(itdragonStr, 'itdragonblog')}"/></p>
    <p>equalsIgnoreCase : <span th:text="${#strings.equalsIgnoreCase(itdragonStr, 'itdragonblog')}"/></p>
    <p>indexOf : <span th:text="${#strings.indexOf(itdragonStr, 'r')}"/></p>
    <p>substring : <span th:text="${#strings.substring(itdragonStr, 2, 8)}"/></p>
    <p>replace : <span th:text="${#strings.replace(itdragonStr, 'it', 'IT')}"/></p>
    <p>startsWith : <span th:text="${#strings.startsWith(itdragonStr, 'it')}"/></p>
    <p>contains : <span th:text="${#strings.contains(itdragonStr, 'IT')}"/></p>
</div>

<h3>#numbers </h3>
<div>
    <p>formatDecimal 整数部分随意,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatDecimal(itdragonNum, 0, 2)}"/></p>
    <p>formatDecimal 整数部分保留五位数,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatDecimal(itdragonNum, 5, 2)}"/></p>
</div>

<h3>#bools </h3>
<div th:if="${#bools.isTrue(itdragonBool)}">
    <p th:text="${itdragonBool}"></p>
</div>

<h3>#arrays </h3>
<div th:if="${not #arrays.isEmpty(itdragonArray)}">
    <p>length : <span th:text="${#arrays.length(itdragonArray)}"/></p>
    <p>contains : <span th:text="${#arrays.contains(itdragonArray, 5)}"/></p>
    <p>containsAll : <span th:text="${#arrays.containsAll(itdragonArray, itdragonArray)}"/></p>
</div>

<h3>#lists </h3>
<div th:if="${not #lists.isEmpty(itdragonList)}">
    <p>size : <span th:text="${#lists.size(itdragonList)}"/></p>
    <p>contains : <span th:text="${#lists.contains(itdragonList, 0)}"/></p>
    <p>sort : <span th:text="${#lists.sort(itdragonList)}"/></p>
</div>

<h3>#maps </h3>
<div th:if="${not #maps.isEmpty(itdragonMap)}">
    <p>size : <span th:text="${#maps.size(itdragonMap)}"/></p>
    <p>containsKey : <span th:text="${#maps.containsKey(itdragonMap, 'thName')}"/></p>
    <p>containsValue : <span th:text="${#maps.containsValue(itdragonMap, '#maps')}"/></p>
</div>

<h3>#dates </h3>
<div>
    <p>format : <span th:text="${#dates.format(itdragonDate)}"/></p>
    <p>custom format : <span th:text="${#dates.format(itdragonDate, 'yyyy-MM-dd HH:mm:ss')}"/></p>
    <p>day : <span th:text="${#dates.day(itdragonDate)}"/></p>
    <p>month : <span th:text="${#dates.month(itdragonDate)}"/></p>
    <p>monthName : <span th:text="${#dates.monthName(itdragonDate)}"/></p>
    <p>year : <span th:text="${#dates.year(itdragonDate)}"/></p>
    <p>dayOfWeekName : <span th:text="${#dates.dayOfWeekName(itdragonDate)}"/></p>
    <p>hour : <span th:text="${#dates.hour(itdragonDate)}"/></p>
    <p>minute : <span th:text="${#dates.minute(itdragonDate)}"/></p>
    <p>second : <span th:text="${#dates.second(itdragonDate)}"/></p>
    <p>createNow : <span th:text="${#dates.createNow()}"/></p>
</div>
代码语言:javascript
复制
@RequestMapping("varexpressions")
public String varexpressions(ModelMap map) {
  map.put("itdragonStr", "itdragonBlog");
  map.put("itdragonBool", true);
  map.put("itdragonArray", new Integer[]{1,2,3,4});
  map.put("itdragonList", Arrays.asList(1,3,2,4,0));
  Map itdragonMap = new HashMap();
  itdragonMap.put("thName", "${#...}");
  itdragonMap.put("desc", "变量表达式内置方法");
  map.put("itdragonMap", itdragonMap);
  map.put("itdragonDate", new Date());
  map.put("itdragonNum", 888.888D);
  return "grammar/varexpressions";
}

三元运算、条件表达式

代码语言:javascript
复制
a? b:c   # 如果a为true,则输出b,否则输入c。     相当于 (if  else) 
a? b     # 如果a为true,则输出b,否则输入'' 。   相当于 a? b:''

默认表达式

${a}?: b 相当于 ${a} ? ${a}:b 如果 a不为空时,输出a的值,否则输入b的值。

字符串连接、拼接

  • 通过 ' '+ 拼接字符串 ;
  • | a,b,c|拼接字符串(推荐);
代码语言:javascript
复制
<!-- 直接输出变量 -->
变量:[[${hello}]]

<!-- 通过 '' 和 + 拼接字符串 -->
<div th:text="'哈哈,'+${hello}+','+${name}+'!'" ></div>

<!-- 通过 | | 拼接字符串(推荐) -->
<div th:text="|哈哈,${hello},${name}!|" ></div>

布尔操作

  • and,or 二元操作符
  • !,not 非(一元操作符)

语法

th:text

  可对表达式或变量求值,并将结果显示在其被包含的 html 标签体内替换原有html文本   文本连接:用“+”符号,若是变量表达式也可以用“|”符号   优先级不高:order=7

th:utext

  相比于th:text的纯文本显示,th:utext支持html的文本显示。

代码语言:javascript
复制
<p th:utext="${htmlcontent}">content</p>

th:id

div id声明,类似html标签中的id属性。

代码语言:javascript
复制
<div class="student" th:id = "stu+(${rowStat.index}+1)"></div>

th:action

  定义后台控制器路径,类似<form>标签的action属性。

代码语言:javascript
复制
<form id="login-form" th:action="@{/login}">...</form>

th:method

  设置请求的方法

代码语言:javascript
复制
<form id="from" th:action="@{/login}" th:method="post">...</form>

th:name

  设置表单名称

代码语言:javascript
复制
<input th:type="text" th:id="${user.age}" th:name="${user.age}"/>

th:field

  常用于表单字段绑定。通常与th:object一起使用。 属性绑定、集合绑定。 th:field取值时,后台不能用reques.setAttribute()来传值,可以用model.addAttribute()来传值;而这两种方式th:value都可以接收。   使用th:field属性可以在页面初始化的时候给对应的元素生成id

代码语言:javascript
复制
<form id="login-form" th:action="@{/login}" th:object="${loginBean}">
    <input type="text" value="" th:field="*{username}"></input>
    <input type="text" value="" th:field="*{user[0].username}"></input>
</form>

th:object

  用于表单数据对象绑定,将表单绑定到后台controller的一个JavaBean参数。常与th:field一起使用进行表单数据绑定   声明变量,一般和*{}一起配合使用,达到偷懒的效果。   优先级一般:order=4

代码语言:javascript
复制
<form id="login-form" th:action="@{/login}" th:object="${loginBean}">...</form>

th:src

  用于外部资源引入,类似于<script>标签的src属性,常与@{}一起使用。

代码语言:javascript
复制
<script th:src="@{/resources/js/jquery/jquery.json-2.4.min.js}"

th:value

  用于标签复制,类似<option>标签的value属性。   设置当前元素的value值,类似修改指定属性的还有th:src,th:href。   优先级不高:order=6

代码语言:javascript
复制
<option th:value="Adult">Adult</option>
<input  id="msg" type="hidden" th:value="${msg}" />

th:attr

 把数据以属性值的保存起来,多个属性时,用逗号(,)的方式分割。  修改任意属性,实际开发中用的较少,因为有丰富的其他th属性帮忙,类似的还有th:attrappendth:attrprepend。  优先级一般:order=5

代码语言:javascript
复制
th:attr="attr1=${value1}, attr2=${value2}"

th:attr 标签定义多个属性的使用方式已经过时了,不推荐使用。 推荐的方式

代码语言:javascript
复制
attr1="${value1}"  attr2="${value2}"

实例:

代码语言:javascript
复制
<div id="cityBtn" class="btn" th:attr="data-cityId=${cityId}, data-regionId=${regionId}" th:text="${cityName}" >
    <span class="fa fa-angle-down"></span>
</div>

public String thymeleaf(ModelMap map) {
    map.put("cityName", "北京");
    map.put("cityId", "00001");
    map.put("regionId", "010");
    return "/grammar/thymeleaf";
}
// 解析后:
<div id="cityBtn" class="btn" data-cityId="00001" data-regionId="010" >北京</div>

th:href

 URL链接中传参。url 的参数 写在 括号内,多个参数时,用逗号分割  定义超链接,类似<a>标签的href 属性。value形式为@{/logout}

代码语言:javascript
复制
<a th:href="@{/show( id=${id } ,name=${name} )}">相对路径-传参</a>
<!-- 解析后: -->
<a href="/show?id=12&amp;name=zhangsan">相对路径-传参</a>

th:attrappend、th:attrprepend

 前置和后置添加属性值

代码语言:javascript
复制
<input type="button" value="Do it!" class="btn" th:attrappend="class=${' ' + cssStyle}" />
<!-- 编译后 -->
<input type="button" value="Do it!" class="btn warning" />

th:classappend、th:styleappend

 两个特定的添加属性。在不改变标签内class属性的前提下,添加某class/style样式

代码语言:javascript
复制
<div class="checkbox-custom" th:classappend="${captchaEnabled==false} ? 'm-t': ''">

th:switch、th:case

代码语言:javascript
复制
<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
</div>

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>

th:fragment、th:insert 、th:replace、th:include

 我们可以使用th:fragment属性来定义一个模板,声明定义该属性的div为模板片段,常用于头文件、页尾文件的引入。常与th:includeth:replace一起使用。  代码片段引入时传参。 fragment:定义代码块,方便被th:insert引用。优先级最低:order=8 insert 、replace、include:三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景。优先级最高:order=1

代码语言:javascript
复制
@RequestMapping("/contentPage2")
public String contentPage2(ModelMap map) {
    map.put("varA", "aaaaaa");
    map.put("varB", "bbbbbbb");
    return "/fragments/contentPage2";
}
代码语言:javascript
复制
<!-- /fragments/pagefrag3.html 代码片段: -->
<div th:fragment="frag (varC,varD)">
    <p th:text="${varC} + ' - ' + ${varD}">...</p>
</div>

<!-- contentPage2.html: -->
<div th:include="fragments/pagefrag3::frag(${varA},${varB})">...</div>

对于 th:include="fragments/pagefrag3::frag(varC=${varA},varD=${varB})指定参数名的方式时

  • 代码片段中也有对应的参数名,否则报错;
  • 代码片段中是按照参数名的顺序来的, 无关主页面与代码片段指定的参数名是否一致。

th:inline

 内联。将表达式直接写⼊我们的HTML⽂本。 [[...]][(...)]中的表达式被认为是在Thymeleaf中内联的表达式。  thymeleaf 在html标签内可通过th标签加${}表达式访问model里的对象数据。  但如果不想通过th标签,而是简单地访问model对象数据,或是想在javascript代码块里访问model中的数据,则要使用内联的方法。 th:inline 内联的取值有三种:textjavascriptnone  使用方式:[[${ 变量名 }]]

th:inline=“text” 文本内联
代码语言:javascript
复制
<p>Hello, [[${name}]]!</p>

约等于th:tex 标签

代码语言:javascript
复制
<p>Hello, <span th:text="${name}">Sebastian</span>!</p>
th:inline=“javascript” 脚本内联

 在javascript中 获取变量值。

代码语言:javascript
复制
<script type="text/javascript" th:inline="javascript">	
    var max =  [[${name}]];
    console.log(max); 
</script>

 由于thymeleaf 的版本不同,有时变量外层要加引号(单引号,双引号都可以),即var max = "[[${name}]]"

th:inline=“none” 禁止内联

 因为内联的表达式是双层中括号[[${ 变量名 }]] , 当使用数组二维数组时,就会与thymleaf 语法冲突,如果还想使用数据,此时必须禁止内联th:inline="none",才使用常规的 javascript语法。

代码语言:javascript
复制
<script type="text/javascript" th:inline="none">
    var max = document.getElementById("maxSumOfDateInYear").value;
    var data = [["2012-05-07", 6], ["2012-04-16", 4]];
    console.log(max);
    console.log(data);
</script>

th:each

 遍历循环元素,和th:text或th:value一起使用。注意该属性修饰的标签位置。  优先级很高:order=2  在 th:each 迭代的同时,我们也可以获取迭代的状态对象 stat stat对象包 含以下属性:

  • index,从0开始的角标
  • count,元素的个数,从1开始
  • size,总元素个数
  • current,当前遍历到的元素
  • even/odd,返回是否为奇偶,boolean值
  • first/last,返回是否为第一或最后,boolean值
代码语言:javascript
复制
<div th:each="user,stat : ${userList}">
    <span th:text="${stat.index}">index</span>
    <span th:text="${user.name}">name</span>
    <span th:text="${user.age}">age</span>
    <span th:text="${user.address}">address</span>
    <span th:if="${stat.even}">奇行</span>
    <span th:if="${stat.odd}">偶行</span>
    <span th:if="${stat.first}">第一行</span>
    <span th:if="${stat.last}">最后一行</span>
</div>

th:remove

 删除模板片段,th:remove 支持条件表达式 th:remove 的值如下:

  • all : 删除包含标签和所有的孩子 ;
  • body : 不包含标记删除,但删除其所有的孩子 ;
  • tag : 包含标记的删除,但不删除它的孩子 ;
  • all-but-first : 删除所有包含标签的孩子,除了第一个 ;
  • none :什么也不做。这个值是有用的动态评估 。

th:with

 定义局部变量,作用域限定于子标签以内。在作用域外使用,没有任何输出,为空的  一次性定义多个变量,用逗号分割。

代码语言:javascript
复制
<div th:with="hello2=${name}+',你好',cityName2=${cityName}+',真美丽' ">
	<div  th:text="${hello2}"></div>
	<div  th:text="${cityName2}"></div>
</div>

th:with 定义的变量可以复用,但必须在作用域内

代码语言:javascript
复制
<!-- myDream 复用了 cityName2 的值 -->
<div th:with="cityName2=${cityName}+',真美丽' , myDream=${cityName2}+',我真的好想去' ">
	<div  th:text="${myDream}"></div>
</div>

th:block

 空标签,标签本身不显示 <th:block> </th:block>是 Thymeleaf 提供的唯一的一个Thymeleaf块级元素,其特殊性在于Thymeleaf模板引擎在处理 <th:block> 的时候会删掉它本身,标签本身不显示,而保留其内容,应用场景主要如下:

  • 同时控制相连两个标签是否显示
代码语言:javascript
复制
<th:block th:if="${id}==12">
	<div id="div1">
		张三的新增权限
	</div>
	<div id="div2">
		张三的删除权限
	</div>
</th:block>
  • 循环同级标签 比如在表格中需要使用th:each 循环 两个 tr,在不知道 th:block 标签时,可能会用 th:each 配合 th:if 使用,但是使用 th:block就简单了
代码语言:javascript
复制
<table>
	<th:block th:each="...">
		<tr>...</tr>
		<tr>...</tr>
	</th:block>
</table>
  • 用于占位符
代码语言:javascript
复制
<!-- 额外添加的链接 -->
<th:block th:replace="${links}" />

th:if

 优先级较高:order=3

  • 多条件判断,使用&&、||
代码语言:javascript
复制
<ul class="nav nav-second-level">
   <li th:each="cmenu : ${menu.children}">
       <a class="J_menuItem"  th:if="${cmenu.text!= '角色管理' && cmenu.text!= '系统菜单'}"
           href="graph_echarts.html" th:text="${cmenu.text}"
           th:href="${cmenu.attributes.url}">系统管理</a>
   </li>
</ul>
  • if elseif elseth:switch th:case 如果要实现if elseif else 判断表达式,在thymeleaf要使用 th:switch 代替,th:case="*"表示默认,需写在最后
代码语言:javascript
复制
<div class="top" th:switch="${area}">
   <div class="logo" th:case="'a'">
       <img th:src="@{/static/images/logo-A.png}">
   </div>
   <div class="logo" th:case="'b'">
       <img th:src="@{/static/images/logo-B.png}">
   </div>
   <div class="logo" th:case="*">
       <img th:src="@{/static/images/logo-c.png}">
   </div>
</div>

th:unless

 与th:if相反,条件不成立时才成立

th:onclick

 点击事件

代码语言:javascript
复制
<td th:onclick = "'getCollect()'"></td>

th:style

 设置样式

代码语言:javascript
复制
<div th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"></div>

常见用法

(本部分内容绝大部分转载自:https://blog.csdn.net/sunnyzyq/article/details/86685697)

输入框中显示用户姓名

代码语言:javascript
复制
姓名:<input type="text" name="name" th:value="${user.name}">

下拉选择月份

 其中monthList为月份数据,th:field为回显数据(这里回显值为query对象中的mid属性)

代码语言:javascript
复制
<span>月份:</span>
<select name="mid" th:field="${query.mid}">
    <option th:each="each : ${monthList}" th:text="${each.name}"  th:value="${monthList.id}"></option>
</select>

链接

代码语言:javascript
复制
<!-- 显示用户姓名,点击姓名会自动跳转到用户详情页面,这里后面会携带一个id参数。-->
<a th:href="@{/user/detail(id=${user.id})}"  th:text="${user.name}"></a>
<!-- 用户点击自己的详情页面,不携带参数(id后台session中获取)。  -->
<a th:href="@{'/system/dis/user/detail'}">个人详情</a>

判断条件

 只有当用户状态为2时,才支持编辑操作

代码语言:javascript
复制
<a th:unless="${user.status==2}">编辑</a>

循环

 展示用户列表

代码语言:javascript
复制
<table>
    <tr>
        <th width="20%">姓名</th>
        <th width="10%">年龄</th>
        <th width="70%">地址</th>
    </tr>
    <tr th:each="user:${userList}">
        <td th:text="${user.name}"></td>
        <td th:text="${user.age}"></td>
        <td th:text="${user.address}"></td>
    </tr>
</table>

页面引用

 引用工程system文件夹下的page.html文件

代码语言:javascript
复制
<div th:replace="system/page"></div>

时间格式化

 格式化后台Date类型字段createTime,显示为 yyyy-MM-dd 日期格式

代码语言:javascript
复制
创建时间:<input type="text" th:value="${#calendars.format(batch.createTime,'yyyy-MM-dd')}">

拼接

 用两条竖线包起来,里面可以随意拼接

代码语言:javascript
复制
<a th:onclick="|deleteById('${user.id}')|">删除</a>

显示html内容

 如博客内容显示:需要将博客中的图片、链接等按原排版显示出来

代码语言:javascript
复制
<div th:utext="${boke.content}"></div>

表单提交

代码语言:javascript
复制
<form id="login-form" th:action="@{/login}" th:object="${student}">
    <input type="text" placeholder="id" th:field="*{id}">
    <input type="text" placeholder="name" th:field="*{name}">
    <input type="text" placeholder="age" th:field="*{age}">
    <button type="submit">submit</button>
</form>
代码语言:javascript
复制
@RequestMapping("/login")
public String login(@ModelAttribute Student student, Model model) {
    Integer id = student.getId();
    String name = student.getName();
    Integer age = student.getAge();
    System.out.println(student);
    return "main";
}

说明:

  • formth:object绑定表单对象,th:field对应对象中的变量
  • contriller方法中使用@ModelAttribute映射表单对象,使用getter方法获取值
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前置操作
  • Model、ModelMap、ModelAndView
  • 注意点
  • 具体配置
    • 基本内容样式
      • 表达式
        • 简单表达式
        • 常用的内置对象
        • 常用的内置方法
        • 三元运算、条件表达式
        • 默认表达式
        • 字符串连接、拼接
        • 布尔操作
      • 语法
        • th:text
        • th:utext
        • th:id
        • th:action
        • th:method
        • th:name
        • th:field
        • th:object
        • th:src
        • th:value
        • th:attr
        • th:href
        • th:attrappend、th:attrprepend
        • th:classappend、th:styleappend
        • th:switch、th:case
        • th:fragment、th:insert 、th:replace、th:include
        • th:inline
        • th:each
        • th:remove
        • th:with
        • th:block
        • th:if
        • th:unless
        • th:onclick
        • th:style
      • 常见用法
        • 输入框中显示用户姓名
        • 下拉选择月份
        • 链接
        • 判断条件
        • 循环
        • 页面引用
        • 时间格式化
        • 拼接
        • 显示html内容
        • 表单提交
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档