1.thymleaf 两种赋值方式
| 关键字 | 用法 |
|---|
| th:value | < p th:value="${list.name}"> </p> |
| [[${ }]] | <p> [[${ liat.name }]] </p> |
2. 判断后台传入的对象是否为空
| 关键字 | 用法 |
|---|
| isEmpty | th:if="${not #lists.isEmpty(schoolObj)}" |
//不为空
th:if="${not #lists.isEmpty(schoolObj)}"
//为空
th:if="${#lists.isEmpty(schoolObj)}"
<option th:if="${not #lists.isEmpty(schoolObj)}" value="">全部</option>
如果schoolObj对象不为空,就展示后面的‘全部’
3.遍历对象
| 关键字 | 用法 |
|---|
| th:each | th:each=“obj,schoolStat:${schoolObj}” |
//取值方式一:直接在展示数据的地方用[[${obj}]]
<tr th:each="list,listStat:${listAll}">
<td>[[${list.name}]]</td>
</tr>
//取值方式二:或者通过对象.的形式取出对象中具体的值
<tr th:each="list,listStat:${listAll}">
<td th:value="${list.name}"> </td>
</tr>
| 关键字 | 描述 |
|---|
| index | 当前迭代对象的index(从0开始计算) |
| count | 当前迭代对象的index(从1开始计算) |
| size | 被迭代对象的大小 |
| current | 当前迭代变量 |
| even/odd | 布尔值,当前循环是否是偶数/奇数(从0开始计算) |
| first | 布尔值,当前循环是否是第一个 (true:是 false:不是) |
| last | 布尔值,当前循环是否是最后一个(true:是 false:不是) |
//使用三元表达式添加class属性,若索引是0,也就是从第一个开始(eq是等于)给标签添加class属性
<li th:each="catalog,catalogStat:${catalogArr}" th:class="${catalogStat.index eq 0?'cur':''}" > </li>
//使用三元表达式,动态给标签添加样式.用了关键字last
<div th:each="chapter,chapterStat:${cata.children}" th:style="${chapterStat.last?'margin-bottom: 1.5rem;':''}">
4.th:selected选择框
<option th:selected="${obj.name eq schoolName}">[[${obj.name}]]</option>
解释:如果obj对象中的name等于schoolName,那么选择框就展示obj取到的name对应的值
5.三元表达式动态给标签添加样式
| 关键字 | 用法 |
|---|
| th:style | <div th:style="${cataStat.index gt 0?‘display:none’:’’}"> |
6.三元表达式动态给标签添加class属性
| 关键字 | 用法 |
|---|
| th:style | <li th:class="${catalogStat.index eq 0?‘cur’ : ’ ’ }" > </li> |
7.链接地址引入
| 关键字 | 取值方式 | 图片地址直接引入方式 |
|---|
| th:src | th:src="${ teac.avatar}" | th:src="@{/img/heaard.jpg}" |
8.解析文本内容
| 关键字 | 描述 | 用法 |
|---|
| th:text | 解析文本,不能解析html内容 | th:text="${obj.des}" |
| th:utext | 可以解析html标签 | th:utext="${teac.style}" |
| th:utext | 解析带空行的纯文本内容 | 见下例1: |
例1:<p th:utext="${#strings.unescapeJava(#strings.replace(#strings.escapeJava(dataObj.description),'\n','<br/>'))}"></p >
9.截取字符串
| 关键字 | 描述 | 用法 |
|---|
| #string.substring(data,0,2) | data是要截取的字符串,从0索引截取到2索引 | 见例1: |
| #string.substring(data,2) | 从索引2开始截取,返回后面的部分 | 见例2: |
例1:<p th:text="${#strings.substring(dataObj,0,2)}"></p>
例2:<p th:text="${#strings.substring(dataObj,2)}"></p>
10.定义局部变量
| 关键字 | 描述 | 用法 |
|---|
| th:with | 定义局部变量 | th:with=“time=123” |
取值方式:${time}