当前位置 博文首页 > zhtbs的博客:(项目实战干货)Spring boot 中Thymeleaf 模板 ht
? 在Spring boot 项目开发中,会常常使用到Thymeleaf模板。在对Thymeleaf模板标签的使用技巧,有的人不是很熟悉。这篇文章专门介绍一下模板标签的使用技巧。静态原型中(html页面)Thymeleaf元素与html元素相结合使用的说明与代码例子。文中会提高大量Thymeleaf标签的属性介绍和使用的逻辑示例代码。
pom.xml 项目中使用的Thymeleaf版本
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
? Thymeleaf模板中的使用文字内联标签,需要在使用的html元素上加上文字内联标签标记。
<body th:inline="text">
...
</body>
<script th:inline="javascript">
...
</script>
? th:block
仅是一个属性容器,允许模板开发人员指定他们想要的任何属性。Thymeleaf执行完成后,th:block标签不会在html页面中保存下来,它只是逻辑标签。
th:each
是循环逻辑标签,负责迭代集合中数据到显示到html页中来。
th:each=“迭代器名称: 集 合 元 素 的 名 称 " 。 例 如 : t h : e a c h = " u s e r : {集合元素的名称}"。 例如: th:each="user: 集合元素的名称"。例如:th:each="user:{users}”
<body th:inline="text">
<table>
<tr>
<td>名称</td>
<td>地址</td>
</tr>
<th:block th:each="user:${users}">
<tr>
<td th:text="${user.name}">...</td>
<td th:text="${user.address}">...</td>
</tr>
</th:block>
</table>
</body>
? javascript中 [# th:each=""]
循环遍历也可以使用文字关联标签。
例如:[# th:each=“item: l i s t " ] [ ( {list}"] [( list"][({item.name})]” [/]
<script th:inline="javascript">
[# th:each="item:${users}"]
[(${item.name})]
[(${item.address})]
[/]
</script>
引用名称+Stat 例子:itemStat 遍历循环的公共属性引用名字
index
属性。count
属性。size
属性。current
属性。even/odd
布尔属性。first
布尔属性。last
布尔属性。<table>
<tr>
<td>名称</td>
<td>地址</td>
</tr>
<th:block th:each="user:${users}">
<tr th:class="${userStat.odd}?'odd'"><--判断是否是偶数列-->
<td th:text="${user.name}">...</td>
<td th:text="${user.address}">...</td>
</tr>
</th:block>
</table>
? th:text
显示文本内容标签,可以将循环中遍历的内容通过标签的形式显示在html页面中。
[(${name})]
也可以使用文本标签的形式将内容显示在html页面中,这个方法更加灵活,但是前提必须要在body元素中加入th:inline="text"标记参考 1文字内联标签引入。
<table>
<tr>
<td>名称</td>
<td>地址</td>
</tr>
<th:block th:each="user : ${users}">
<tr>
<td th:text="${user.name}">...</td> //th:text 标签使用方法
<td>[(${user.address})]</td> //[(${引用})]文字内联使用方法
</tr>
</th:block>
</table>
? @{'字符串'+引用内容}
将固定的字符串与引用变量组合成新的字符串内容。
? 例如@{’…/WbsItemManageContorller/finduser?id=’+${item.id}}
? html 显示的字符串’…/WbsItemManageContorller/finduser?id=1’
<table>
<tr>
<td>名称</td>
<td>地址</td>
<td>编辑</td>
</tr>
<th:block th:each="user : ${users}">
<tr>
<td th:text="${user.name}">...</td> //th:text 标签使用方法
<td>[(${user.address})]</td> //[(${引用})]文字内联使用方法
<td>
<a th:href="@{'../WbsItemManageContorller/finduser?id='+${user.id}}">
修改
</a>
</td>
</tr>
</th:block>
</table>
例子 th:onClick:
<table>
<tr>
<td>名称</td>
<td>地址</td>
<td>编辑</td>
</tr>
<th:block th:each="user:${users}">
<tr>
<td th:text="${user.name}">...</td> //th:text 标签使用方法
<td>[(${user.address})]</td> //[(${引用})]文字内联使用方法
<td>
<a th:href="@{'../WbsItemManageContorller/finduser?id='+${user.id}}">
修改
</a>
<div th:onClick="@{'ondel('+${item.id}+')'}">删除</div>
//@{}字符串拼接语法
</td>
</tr>
</th:block>
</table>
? th:if通过条件判断,来决定符合条件的元素是否存在于html页面中来。或者通过