Thymeleaf的特点
Thymeleaf 模板引擎具有以下特点:
- 动静结合:Thymeleaf 既可以直接使用浏览器打开,查看页面的静态效果,也可以通过 Web 应用程序进行访问,查看动态页面效果。
- 开箱即用:Thymeleaf 提供了 Spring 标准方言以及一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
- 多方言支持:它提供了 Thymeleaf 标准和 Spring 标准两种方言,可以直接套用模板实现 JSTL、 OGNL 表达式;必要时,开发人员也可以扩展和创建自定义的方言。
- 与 SpringBoot 完美整合:SpringBoot 为 Thymeleaf 提供了的默认配置,并且还为 Thymeleaf 设置了视图解析器,因此 Thymeleaf 可以与 Spring Boot 完美整合。
-
内联表达式
[[...]] 相当于 th:text ,即会将HTML代码转义。
[(...)] 相当于 th:utext, 不会转义HTML代码。
不想开启内联表达式,可以使用 th:inline="none"
关闭
<div th:inline="none">[(${msg})]</div>
想要开启的话使用 th:inline="text"
,默认情况下就是text
在JS中使用内联,需要开启 th:inline="javascript"
<script th:inline="javascript">
const blog=[[${blog}]]//这种情况用浏览器直接预览会报错
const blog=/*[[${blog}]]*/ //这种情况用浏览器预览不会报错
console.log(blog)
</script>
表达式基本对象
${#ctx.locale}
${#ctx.variableName}
${#ctx.request}
${#ctx.response}
${param.id
}
${session.loginId}
${#request}
表达式实用对象
时间的格式化
${#dates.format(date,'yyyy-MM-dd HH:mm:ss')}
数字的格式化
${#nambers.formatPercent(num)}
数组的格式化
${#nambers.arrayFormInteger(array,3)}
不足三位,前面补0
将对象转化成字符串(前提:定义的对象中必须包含toString方法)
${#strings.toString(obj)}
加一个命名空间
xmlns:th="http://www.thymeleaf.org"
常用属性
th:text="${msg}" //会将HTML代码转义
th:utext="${msg}" //不会将HTML代码转义
th:value //给属性赋值
th:object //用于设置选定对象
th:if //条件判断,可以和th:unless配合使用
th:switch //选择判断,需要配合th:case使用
th:each //循环迭代
th:href //设置链接地址
渲染拼接
<title th:text="|${User.username}的个人主页|">
或
<title th:text="|${User.username}+的个人主页|">
object对象的使用
//th:object //用于设置选定对象
<div th:object="${blog}">
<p th:text="*{title}"></p>
<p th:text="*{content}"></p>
<p th:text="*{createTime}"></p>
<p th:text="*{status}"></p>
<div>
//要用*号
if属性
<div th:if="${false}">测试</div>
<div th:if=""${blog.status}==1">测试</div>
<div th:if=""${blog.status==1}">测试</div>
switch属性
<div th:switch="*{isWriter}">
<button th:case="1" type="button"> 创建与作品管理</button>
<button th:case="0" type="button"> 成为作者</button>
<button th:case="*" type="button"> 其他</button>
</div>
each循环迭代
这次写项目要求使用Thymeleaf,所以就总结一下自己学到的一些知识。😥😓😭😊