String Boot-thymeleaf使用(四)
简介
Thymeleaf是面向Web和独立环境的现代服务器端Java模板引擎,能够处理HTML,XML,JavaScript,CSS甚至纯文本。,可以完全替代jsp,也是spring boot官方推荐的模版引擎
Thymeleaf优势
1.可以独立运行 前后端分离的时候 前端可以直接运行模版进行样式调整
2.不破坏html整体结构,更贴向html
3.可以使用模版实现JSTL、 OGNL表达式效果
Thymeleaf简单使用
1.引入pom依赖
<!--thymeleaf模版--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
properties配置 根据实际需要配置
# THYMELEAF (ThymeleafAutoConfiguration)
#开启模板缓存(默认值:true)
spring.thymeleaf.cache=false
#Check that the template exists before rendering it.
spring.thymeleaf.check-template=true
#检查模板位置是否正确(默认值:true)
spring.thymeleaf.check-template-location=true
#开启MVC Thymeleaf视图解析(默认值:true)
spring.thymeleaf.enabled=true
#模板编码
spring.thymeleaf.encoding=UTF-8
#要被排除在解析之外的视图名称列表,用逗号分隔
#spring.thymeleaf.excluded-view-names=
#要运用于模板之上的模板模式。另见StandardTemplate-ModeHandlers(默认值:HTML5)
spring.thymeleaf.mode=HTML5
#在构建URL时添加到视图名称前的前缀(默认值:classpath:/templates/)
spring.thymeleaf.prefix=classpath:/templates/
#在构建URL时添加到视图名称后的后缀(默认值:.html)
spring.thymeleaf.suffix=.html
#Thymeleaf模板解析器在解析器链中的顺序。默认情况下,它排第一位。顺序从1开始,只有在定义了额外的TemplateResolver Bean时才需要设置这个属性。
#spring.thymeleaf.template-resolver-order=
#可解析的视图名称列表,用逗号分隔
#spring.thymeleaf.view-names=
2.新建一个Contorller
@Controller public class HelloWordContorller { @RequestMapping("/helloword") public String helloWord(Model model){ List<StudentConfig> studentConfigList=new ArrayList<StudentConfig>(); for(int i=0;i<10;i++){ studentConfigList.add(new StudentConfig("小明"+i,i)); } model.addAttribute("list",studentConfigList); return "index"; } }
3.再resource/template下面新建一个html页面
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> table td{ text-align: center; } </style> </head> <body> <table style="width:100%"> <thead> <tr> <th>学生姓名</th> <th>学生年龄</th> </tr> </thead> <tbody> <tr th:each="item : ${list}"> <td th:text="${item.name}">小明</td> <td th:text="${item.age}">20</td> </tr> </tbody> </table> </body> </html>
xmlns:th="http://www.thymeleaf.org" 将静态页面转换为动态的视图,需要进行动态处理的元素将使用“th:”前缀。
访问输出
thymeleaf模版引擎跟jsp比起来是否更易读。如果写jsp的话 里面有很多自定义标签 前端人员根本也无法阅读
还有就是模版是html是可以直接运行的
4.找到模版地址
打开
所以前端是可以直接根据模版进行样式调整
常用标签
遍历
<tr th:each="item : ${list}"> <td th:text="${item.name}">小明</td> <td th:text="${item.age}">20</td> </tr>
赋值
text赋值
<td th:text="${item.name}">小明</td> <td th:text="${item.age}">20</td>
html赋值
<p th:utext="${htmlcontent}">conten</p>
value赋值
<input type="text" th:value="${user.name}" />
三元运算符
<td th:text="${item.sex==0?'男':'女'}">男</td>
if else
<div th:if="${islogin}">已登录</div> <div th:unless="${islogin}"><a th:href="login.html">请登陆</a></div>
th:if是条件成立才渲染 ht:unless则是条件不成立才渲染
Switch
<div th:if="${islogin}"> <div th:switch="${role}"> <p th:case="'admin'">管理员</p> <p th:case="teacher">老师</p> <p th:case="*">普通用户</p> </div> </div> <div th:unless="${islogin}"><a th:href="login.html">请登陆</a></div>
如果登陆判断 当前用户角色 *表示default
Url
th:src
<img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />
th:href
restful风格
<tr th:each="item : ${list}"> <td th:text="${item.name}">小明</td> <td th:text="${item.age}">20</td> <td th:text="${item.sex==0?'男':'女'}">男</td> <td><a th:href="@{'/edit/'+${item.id}}">编辑</a></td> </tr>
?参数传递
<tr th:each="item : ${list}"> <td th:text="${item.name}">小明</td> <td th:text="${item.age}">20</td> <td th:text="${item.sex==0?'男':'女'}">男</td> <td><a th:href="@{/edit/info(id=${item.id})}">编辑1</a></td> </tr>
?多参数传递
<a th:href="@{/edit/info(id=${item.id},age=${item.age})}">编辑1</a>
th:style
设置背景图片
<td><div th:style="'background:url('+@{${item.headPath}}+')'"></div></td>
内嵌变量
- dates : java.util.Date的功能方法类。
- calendars : 类似#dates,面向java.util.Calendar
- numbers : 格式化数字的功能方法类
- strings : 字符串对象的功能类,contains,startWiths,prepending/appending等等。
- objects: 对objects的功能类操作。
- bools: 对布尔值求值的功能方法。
- arrays:对数组的功能类方法。
- lists: 对lists功能类方法
- sets
- maps
- ...
比如格式化日期
<div>系统时间:<label th:text="${#dates.format(new java.util.Date().getTime(), 'yyyy-MM-dd hh:mm:ss')}"></label></div>
根据需求查api吧 太多了
内联js
<script th:inline="javascript"> var username = /*[[${islogin}]]*/ 'Sebastian'; var size = /*[[${islogin}]]*/ 0; </script>
注释表示通过模版引擎渲染 将注释后面的代码将取消渲染 渲染注释里面的模版代码。便于原型显示(直接打开html页面)
模版引擎渲染结果
直接html打开效果
使用th:inline="javascript"开启 [[....]]表示内联文本
js附加代码:
<script th:inline="javascript"> /*[+ var username = /*[[${islogin}]]*/ 'Sebastian'; var size = /*[[${islogin}]]*/ 0; +]*/ </script>
/*[++]*/ 使用模版引擎渲染将正常渲染
模版引擎渲染结果
模版html直接打开结果
js移除代码
<script th:inline="javascript"> /*[- */ var username = /*[[${islogin}]]*/ 'Sebastian'; var size = /*[[${islogin}]]*/ 0; /* -]*/ </script>
跟js添加代码一样 只是是相反 添加模版引擎渲染则渲染 普通html打开则渲染
使用thymeleaf布局
layout布局
引入pom依赖
<dependency> <groupId>nz.net.ultraq.thymeleaf</groupId> <artifactId>thymeleaf-layout-dialect</artifactId> </dependency>
后台管理系统为例子 头部 底部 菜单栏都是固定的。
1.新建一个页面都把架构复制过去 然后改中间那一块内容
缺点:
会导致我们要修改整体风格每个页面都要改,比如随着时间的迭代页面会越来越多。
2.定义好骨架 然后每个部分引用对应的页面
头部引用头部的html 菜单引用菜单的html 底部引用底部的html
缺点:
页面排版要改动的时候 比如 菜单要放到右边 也会导致每个页面都要改动
3.使用模版页面
使用模版页定义好 整体框架,然后每个页面都来引用这个模版 将内容替换到指定位置
模版页定义公共的样式引入 还有整体风格
1。首先创建一个模版页面
layout.html
<!DOCTYPE html> <html lang="en" xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> #header { background-color: black; color: white; text-align: center; padding: 5px; } #nav { line-height: 30px; background-color: #eeeeee; height: 300px; width: 100px; float: left; padding: 5px; } #section { width: 350px; float: left; padding: 10px; } #footer { background-color: black; color: white; clear: both; text-align: center; padding: 5px; } </style> </head> <body> <div id="header"> 头部 </div> <div id="nav"> 菜单 </div> <div layout:fragment="content" id="section"> 内容 </div> <div id="footer"> 底部 </div> </body> </html>
定义命名空间:xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
要填充的区域:layout:fragment="content"
2.创建一个用户列表页面
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout" layout:decorator="layout"> <head> <meta charset="UTF-8"> <title>用户列表</title> <link href="userlist.css" rel="stylesheet" type="text/css"> <!--私有样式--> <style type="text/css"> table td{ text-align: center; } </style> </head> <body> <div layout:fragment="content">用户列表</div> </body> </html> <script type="text/javascript" src="userlist.js"></script> <script type="text/javascript"> $(function(){ alert('dd'); }) </script>
要填充模版页的位置:layout:fragment="content"
定义命名空间 xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout" layout:decorator="layout"
layout:decorator="layout"为模版页路径
效果
渲染后的html
<!DOCTYPE html> <html lang="en"> <head> <title>用户列表</title> <meta charset="UTF-8"> <style type="text/css"> #header { background-color: black; color: white; text-align: center; padding: 5px; } #nav { line-height: 30px; background-color: #eeeeee; height: 300px; width: 100px; float: left; padding: 5px; } #section { width: 350px; float: left; padding: 10px; } #footer { background-color: black; color: white; clear: both; text-align: center; padding: 5px; } </style> <meta charset="UTF-8"> <link href="userlist.css" rel="stylesheet" type="text/css"> <!--私有样式--> <style type="text/css"> table td{ text-align: center; } </style> </head> <body> <div id="header"> 头部 </div> <div id="nav"> 菜单 </div> <div id="section">用户列表</div> <div id="footer"> 底部 </div> </body> </html> <script type="text/javascript" src="userlist.js"></script> <script type="text/javascript"> $(function(){ alert('dd'); }) </script>
可以发现 页面使用的css 和 script 都自动替换到模版页的 head 和底部
这个时候就算我们有上万个页面 页面风格要改变也就只需要改变模版页就行了
th:include
和 th:replace
创建一个广告页advertising.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>广告</title> </head> <body> <div id="advertisingContent" th:fragment="advertisingContent"> 我是广告 </div> </body> </html>
th:fragment="advertisingContent" 引用的时候会用到
页面引用advertisingContent内容
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>主页</title> </head> <body> <div > <div>主页</div> <div th:replace="advertising :: advertisingContent"></div> </div> </body> </html>
th:replace="advertising :: advertisingContent" 为把advertising(页面路径)advertisingContent为哪一块内容(省略则是整个页面)
传递参数
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <style type="text/css"> <!--自定义样式--> </style> </head> <body> <div id="advertisingContent" th:fragment="advertisingContent(name)"> 我是广告<label th:text="${name}"></label> </div> </body> </html>
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>主页</title> </head> <body> <div > <div>主页</div> <div th:replace="advertising(name='测试传递参数')"></div> </div> </body> </html>
th:include用法一样
区别
th:include只引用chilren
th:include
th:replacehe 引用包含自身
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!