前言
thymeleaf类似于jsp的模板引擎。结合springboot使用,解决前后端分离问题。
使用的版本:
spring-boot-starter-thymeleaf-2.1.2.RELEASE.jar,对应的maven会自动导入需要的thymeleaf-3.0.11.RELEASE.jar和thymeleaf-spring5-3.0.11.RELEASE.jar。可在项目底下的Maven Dependencies目录下查看。如果需要IDE获得代码提示功能则需要在HTML标签加入
xmlns:th="http://www.thymeleaf.org"<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> hello thymeleaf! </body> </html>thymeleaf所有的标签元素都是以
th:开头。除thymeleaf本身所含有的元素外。HTML元素中所有的标签元素都可以用th:+元素名覆盖。举例:<a href="" th:href=""></a>a标签中有href属性,便可以使用th:href覆盖。img标签含有src属性,则可以使用th:src覆盖代替。
基本属性解释
| th:text="" | th:utext="" | |
|---|---|---|
| 区别 | 不会解析HTML标签;${hello<h1>exp<h1>}输出hello<h1>exp<h1> |
会解析HTML标签:输出helloexp |
[[]]功能和th:text=""相同。区别是th:text=""标签内使用,[[]]标签外使用:如<a>[[${hello}]]</a> |
[()]功能和th:utext=""相同。区别是th:utext=""标签内使用,[()]标签外使用 |
例子
<tr th:each="user:${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.username}"></td>
<td>[[${user.password}]]</td>
<td>[[${user.danWeiTID}]]</td>
<td>
<a class="btn btn-sm btn-primary" th:href="@{/user/}+${user.id}">编辑</a>
<button th:attr="del_uri=@{/user/}+${user.id}" type="submit" class="btn btn-danger deleteBtn">删除</button>
</td>
</tr>
常用表达式
| 标签 | 作用 | 使用举例说明 |
|---|---|---|
${example} |
一般用于获得变量值相关。如example的值 |
<p th:text="${example}">value</p> 说明:如果example存在并且有值,那么便会替代value。 |
@{/assets/exp.css} |
一般用于链接地址,或请求地址使用。 | 1.引入静态资源的地址:<img th:src="@{/assets/img/img.png}"/>。其他样式表,脚本等类似。2. 发送请求地址使用:<form th:action="@{/deleteUser/1001}"> |
~{Commons::topbar} |
片段表达式。一般用于引入一段代码片段 | 引入每个页面都需要的导航栏:有一个Commons.html里面包含一个导航栏代码片<nav th:fragment="topbar"></nav>。当我们需要引入这一个导航栏代码时,只需要在需要引入的位置使用<div th:replace="~{commons::topbar}"></div>引入就好了。语法规则:commons是Commons.html的名字,省略.html后缀。代表从哪个模板里边获取。topbar即这个模板底下使用th:fragment属性命名的标识。 |
实用例子
1. 公共页面抽取
使用th:fragment和th:replace属性。
举例:有一个Commons.html。里面包含每个页面所需要的顶部导航栏,侧部导航栏等等,即每个页面都含有的公共部分,单独抽取出来放在Commons.html页面里。代码片加上
th:fragment属性并取一个唯一的名字用作标识。
Commons.html
<!DOCTYPE html>
<html

本文介绍了Thymeleaf作为SpringBoot的模板引擎,用于前后端分离。讲解了如何进行公共页面抽取,通过`th:include`和`th:fragment`属性实现。此外,还分享了一个开发小技巧,如何使用`th:attrappend`添加自定义属性以配合jQuery操作。
最低0.47元/天 解锁文章
2310

被折叠的 条评论
为什么被折叠?



