- 概念
1、Thymeleaf是Web和独立环境的开源的Java模板引擎,能够处理HTML,XML,JavaScript,CSS甚至纯文本;
2、Thymeleaf可以在Web(基于Servlet)和非Web环境中工作,它更适合在基于MVC的Web应用程序的视图层提供XHTML / HTML5 ,但它甚至可以在脱机环境中处理任何XML文件。它提供完整的Spring Framework集成
3、在Web应用程序中,Thymeleaf旨在成为JSP的完全替代品,并实现自然模板的概念:模板文件,可以直接在浏览器中打开,仍然可以正确显示为网页; - maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
3.语法
- 表达式:
${name} 可用值表达式,变量取值(变量名name又后台传入);
*{name} 所有可用值表达式,从可用值中查找name,如果有上下文,比如上层(即父标签)是object,则查object中的name属性(th:object="")。
#{nmae} 消息表达式,国际化时使用,也可以使用内置的对象,比如date格式化数据;(消息通常指:外部文本抽取模板代码片段到模板文件外面, 使外部文本可以存在另一个文件中)
@{name} 链接表达式,用来配合link,src,href使用的
~{name} 片段表达式,用来引入公共部分代码片段,并进行传值操作使用;
2.运算符
数学:+,-,*,/,%
比较:gt,lt,ge,le,eq,ne
逻辑:and,or,not,!
条件:? : ,?: (默认值,例: value ?: defaultvalue,条件语句也可以不只要?号,相当于没有else)
其他:+(字符串连接),_(禁止转义),||(替换,内容可包含非参数内容,如:<a href="" th:href="@{|xx${value}|}"
3.支持的html5操作(基本所有属性都支持了,只是在前边加了一个th:)
常用标签:
th:id 替换id
th:text 替换标签内文本
th:utext html文本替换,可使文本内的标签生效
th:object 替换对象
th:value 属性赋值
th:with 变量赋值运算,例<div th:with="isEven=${prodStat.count}%2==0"></div>
th:style 替换样式
th:onclick 点击事件
th:each 属性赋值
th:if 条件判断,例:<a th:if="${userId == collect.userId}" >
th:unless 条件判断
th:href 链接地址
th:switch switch选择,和th:case一起使用
th:fragmetn 布局标签
th:include
th:replace
th:selected
th:src
th:inline
th:action
th:remove
th:attr 设置任意标签属性,一般较少用到,因为所有的属性都有对应的th:
4.foreach循环遍历
<tr th:each="data:${getdata}">
<td th:text="${data.id}"></td>
<td th:text="${data.name}"></td>
...
</tr>
5.条件(if,switch)
if示例:
<tr th:each="test:${test}">
<td th:if="${test.Score} gt 0 and ${test.Score} lt 60">差</td>
<td th:if="${test.Score} ge 60 and ${test.Score} le 70">中</td>
...
</tr>
if unless示例:
<tr th:each="test:${test}">
<td th:if="${test.Score} gt 0 and ${test.Score} lt 60">不及格</td>
<td th:unless="${test.Score} gt 0 and ${test.Score} lt 60">及格</td>
</tr>
switch 示例:
<tr th:each="test:${test}">
<td th:switch="${test.male}">
<span th:case="1">男</span>
<span th:case="2">女</span>
<span th:case="*">未知</span>
</td>
</tr>
6.常用
日期格式化:
<td th:text="${#dates.format(content.createDate,'yyyy-MM-dd HH:mm:ss')}"></td>
字符串长度截取:
<td th:if="${#strings.length(content.title) gt 5 } " th:text="${#strings.substring(content.title,0,5) + '…'}"></td>
下拉选择:
<select name="subId" id="subId" lay-verify="" >
<option value="">请选择</option>
<option th:each="channelsub:${subchannels}" th:selected="${channelsub.id == subId}" th:value="${channelsub.id}" th:text="${channelsub.name}"></option>
</select>