首先先建立一个springboot 整合thymealf 的demo
springboot的pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 省略get/set等方法 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
application.yaml 文件
server:
port: 8080
# 关闭缓存 上线的时候要打开
spring:
thymeleaf:
cache: false
这样我们一个springboot整合thymealf 就整合好了 pom application.yaml
我们可以设置下idea 这个项目 update resources 意思是说以后html 页面修改了 我们可以直接看效果 而不用重启 编辑完成之后直接看效果
-----------------------------------------------
1. 我们用th:text 渲染文本 ${} 代表此时数据是从后台传递过来的
thymealf 可以起到一个动态分离的效果 就是
<h1 th:text="${title}">原来的</h1> 默认在页面展示的是原来的 他不报错 通过控制器访问它就会 做个替换
-------------> 下面2个都可以
<div>
<h1 th:text="${title}"></h1>
</div>
<div>
<h1 >[[${title}]]</h1>
</div>
此时不会报错 我们写一个控制器来做到页面跳转
可以使用 th:text 渲染文本 现在如果要做字符串拼接的话
<h1 th:text="'BB'+${title}">原来的</h1> 直接加字符串
也可以
<h1 th:text="|BB${title}|">原来的</h1> 加2个竖线
2.
我可以通过 ${uservo.getAge()} 或者 {uservo.age}
拿到对应属性
<h1 th:text="${uservo.getAge()}"></h1>
<h1 th:text="${uservo.age}"></h1>
呢么如果他的字段多的话 该怎么去处理呢 我不能一个一个的uservo.xxx
右键查看网页源代码 他确实渲染过来了
th:if 是否显示
<h1 th:if="!${uservo.isVip}">会员</h1> 通过if来判断这个元素是否渲染
th:if 是否显示
<h1 th:if="${uservo.isVip}">会员</h1> 通过if来判断这个元素是否渲染
th:each 用来遍历 拿到每一个tag 然后放入文本种 我们循环出来的对象
比如说
<ul>
<li th:each="t:${uservo.tag}" th:text="${t}"></li>
</ul>
网页也正常回显了
然后 switch case
<div th:switch="${uservo.sex}">
<p th:case="1">男</p>
<p th:case="2">女</p>
<!--默认 default 类似于java-->
<p th:case="*">x</p>
</div>
-------------------------------------------------------------
1.js. css 的url 的引入
我在static下写了一个css 样式 同样我们需要java 控制器来跳转到我们的页面上
<link th:href="@{app.css}" rel="stylesheet" >
@{} 可以引入路径 app.css 因为我们创建的是根目录下的
同理 引入js也一样
我们的数据流向是通过 model--->thymeealf的标签到页面的
有些时候这些数据我们同样想通过js拿到
我们想拿到传递过来的User 传到js里面 定义一个user对象 赋值成功
比如说点击事件 th:inline 我们可以用 /*[[${uservo}]]*/{} 这种 拿到
我把他打印出来
<script th:inline="javascript">
const user=/*[[${uservo}]]*/{}
console.log(user)
</script>
同样css也可以渲染
在之前的遍历中 我如果我想要最后一个 变成红色 或者说最后一个赋予这个属性 style样式该怎么做
<ul>
<!--stat 是索引 1,2,3,4-->
<li th:each="t,stat:${uservo.tag}"
th:text="${t}" th:classappend="${stat.last}?'active'"></li>
</ul>
此时当最后一个的时候 我就让他变成红色
------------------------------------------------------------->
组件/碎片
使用th:fragment 来定义一个组件 通过 ~{componet::com1}
来引用这个组件
<div th:replace="~{componet::com1}"></div>
th:replace 是做替换 替换掉当前的div
看 把当前的div 做了替换
呢么还有 <div th:insert="~{componet::com1}"></div>
直接在这个div 里面新加节点
常用的就者2中 我们可以 不使用th:fragment 使用id 这些选择器进行选择 比如说
使用选择器的时候 前面加# 这是id的选择器
thymealf 也可以获取到session. 的值 以及 使用ctx 的上下文对象 这些上下文对象
我们也可以使用时间转化函数 以及这些函数 我们可以把这些函数通过java 传递过来
组件中也可以传值得比如说
我定义一个
<div th:fragment="com5(message)">
<p th:text="${message}"></p>
</div>
我引用得时候
<div th:replace="~{componet::com5('传递的数据')}"></div>
传递 '传递得数据就可以做引用'
组件中如果需要变量的话该怎么办
就可以读取到了 ${uservo.userName}了