4.Thymeleaf 是什么?Thymeleaf标签支持的语法?使用注意事项?

目录


Spring Boot专栏目录(点击进入…)



Thymeleaf模板引擎

(1)Thymeleaf是用来开发Web和独立环境项目的服务器端的Java模版引擎
(2)Spring官方支持的服务的渲染模板中,并不包含Jsp。而是Thymeleaf和Freemarker等,而Thymeleaf与Spring MVC的视图技术,及Spring Boot的自动化配置集成非常完美,几乎没有任何成本,只用关注Thymeleaf的语法即可

Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf

最大的特点:能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用


Thymeleaf 是什么?

简单说,Thymeleaf 是一个跟Velocity、FreeMarker类似的模板引擎,它可以完全替代JSP。相较与其他的模板引擎,有如下三个极吸引人的特点

(1)动静结合
Thymeleaf在有网络和无网络的环境下皆可运行,可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果
静态查看:这是由于它支持html原型,然后在html标签里增加额外的属性来达到模板 + 数据的展示方式。浏览器解释html时会忽略未定义的标签属性,所以Thymeleaf模板可以静态地运行
动态查看:当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示

(2)开箱即用
提供标准和Spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言

(3)多方言支持
Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能

(4)与Spring Boot完美整合
Spring Boot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,可以像操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别


标准表达式语法(四类)

1.变量表达式

变量表达式即OGNL表达式或Spring EL表达式(Spring术语中也叫model attributes)
${session.user.name}
它们将以HTML标签的一个属性来表示:

<span th:text="${book.author.name}">  
<li th:each="book : ${books}"> 

2.选择(星号)表达式

选择表达式很像变量表达式,不过它们用一个预先选择的对象来代替上下文变量容器(map)来执行;选择表达式一般跟在th:object后,直接选择object中的属性
*{customer.name}
被指定的object由th:object属性定义:

<div th:object="${book}">  
	<span th:text="*{title}">...</span>  
</div> 

3.文字国际化表达式

文字国际化表达式允许从一个外部文件获取区域文字信息(.properties),用Key索引Value,还可以提供一组参数(可选)

#{main.title} 
#{message.entrycreated(${entryId})}

可以在模板文件中找到这样的表达式代码:

<table>  
	<th th:text="#{header.address.city}">...</th>  
	<th th:text="#{header.address.country}">...</th>  
</table> 

4.URL表达式

URL表达式指的是把一个有用的上下文或回话信息添加到URL,这个过程经常被叫做URL重写
@{……}:支持决定路径和相对路径。其中相对路径又支持跨上下文调用url和协议的引用(//code.jquery.com/jquery-2.0.3.min.js)

@{/order/list}

URL还可以设置参数:@{/order/details(id=${orderId})}
相对路径:@{…/documents/report}

<form th:action="@{/createOrder}">
<a href="main.html" th:href="@{/main}">

变量表达式和星号表达有什么区别吗?

如果不考虑上下文的情况下,两者没有区别;星号语法评估在选定对象上表达,而不是整个上下文
什么是选定对象?就是父标签的值

<div th:object="${session.user}">
	Name: <span th:text="*{firstName}">Sebastian</span>
	Surname: <span th:text="*{lastName}">Pepper</span>
	Nationality: <span th:text="*{nationality}">Saturn</span>
</div>

完全等价于:

<div th:object="${session.user}">
	Name: <span th:text="${session.user.firstName}">Sebastian</span>
	Surname: <span th:text="${session.user.lastName}">Pepper</span>
	Nationality: <span th:text="${session.user.nationality}">Saturn</span>
</div>

美元符号和星号语法可以混合使用:

<div th:object="${session.user}">
	Name: <span th:text="*{firstName}">Sebastian</span>
	Surname: <span th:text="${session.user.lastName}">Pepper</span>
	Nationality: <span th:text="*{nationality}">Saturn</span>
</div>

表达式支持的语法

(1)字面(Literals)

表达式描述
文本文字(Text literals)‘one text’, ‘Another one!’,…
数字文本(Number literals)0, 34, 3.0, 12.3,…
布尔文本(Boolean literals)true, false
空(Null literal)null
文字标记(Literal tokens)one, sometext, main,…

(2)文本操作(Text operations)

表达式描述
字符串连接(String concatenation)+
文本替换(Literal substitutions)|The name is ${name}|

(3)算术运算(Arithmetic operations)

表达式描述
二元运算符(Binary operators)+, -, *, /, %
减号(单目运算符)Minus sign (unary operator)-

(4)布尔操作(Boolean operations)

表达式描述
二元运算符(Binary operators)and, or
布尔否定(一元运算符)Boolean negation (unary operator)!, not

(5)比较和等价(Comparisons and equality)

表达式描述
比较(Comparators)>, <, >=, <= (gt, lt, ge, le)
等值运算符(Equality operators)==, != (eq, ne)

(6)条件运算符(Conditional operators)

表达式描述
If-then(if) ? (then)
If-then-else(if) ? (then) : (else)
Default(value) ?: (defaultvalue)

所有这些特征可以被组合并嵌套:

'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

语法表

1.基本语法

语法功能介绍实例
th:attr给标签的属性赋值<div th:attr=“id=‘666’,value=‘999’”>
th:id替换id<input th:id=“‘xxx’ + ${collect.id}”/>
th:text文本替换<p th:text=“${collect.description}”>description</p>
th:utext支持html的文本替换<p th:utext=“${htmlcontent}”>conten</p>
th:object替换对象<div th:object=“${session.user}”>
th:value属性赋值<input th:value=“${user.name}” />
th:with变量赋值运算<div th:with=“isEven=${prodStat.count}%2==0”></div>
th:style设置样式th:style=“'display: ’ + (@{(${sitrue} ? ‘none’ : ‘inline- block’)} + ’ '”
th:onclick点击事件th:οnclick=" ‘getCollect()’"
th:each循环<tr th:each=“item:${list}”>
th:if判断条件<a th:if=“${userld == collect.userid}” >
th:unless和th:if判断相反<a th:href=“@{/login}” th:unless=${session.user != null}>Login</a>
th:href链接地址<a th:href=“@{/login}” th:unless=${session.user != null}>Login</a> />
th:switch多路选择配合th:case 使用 被指定为默认选项用th:case=“*”;相当于default <div th:switch=“${user.role}”>
th:caseth:switch的一个分支<p th:case=“‘admin’”>User is an administrator</p>
th:fragment布局标签,定义可引用的代码片段<div th:fragment=“alert”>
th:include布局标签,替换内容到引入的文件<head th:include=“layout :: htmlhead” th:with=“title=‘xx’”></head>
th:replace布局标签,替换整个标签到引入的文件<div th:replace=“fragments/header :: title”></div>
th:selectedselected选择框选中th:selected=“({configObj.dd})”
th:src图片类地址引入<img class=“img-responsive” alt=“App Logo” th:src=“@{/img/logo.png}” />
th:inline定义js脚本可以使用变量<script type=“text/javascript” th: inline=“javascript”>
th:eachtable遍历<tr th:each=“item:{item.tName}”><td th:text=“{item.tAddress}”></td></tr>
th:each下拉菜单遍历<select class=“name”><option>请选择</option><option th:each=“item:{item.tId}” th:text=“${item.tName}” ></option></select>
format日期格式化<span th:text=“${#dates.format(date,‘yyyy-MM-dd hh:mm:ss’)}”></span>
三目运算符<td th:text=“${name==‘zs’}? 张三 : zs”></td>
gt大于(>)
ge大于等于(>=)
eq等于(==)
lt小于(<)
le小于等于(<=)
ne不等于(!=)

2.内置对象常用语法

语法实例功能介绍
日期格式化<span th:text=“${#dates.format(curDate, ‘yyyy-MM-dd HH:mm:ss’)}”></span>使用内置对象dates的format函数即可对日期进行格式化,在format函数中,第一个参数是日期对象,对二两个参数为日期格式(规则跟SimpleDateFormat一样)
数字格式化<span th:text=“${#numbers.formatDecimal(money, 0, 2)}”></span>此示例表示保留两位小数位,整数位自动
数字格式化<span th:text=“${#numbers.formatDecimal(money, 3, 2)}”></span>此示例表示保留两位小数位,3位整数位(不够的前加0)
获取列表长度<span th:text=“${#lists.size(datas)}”></span>使用#lists.size来获取List的长度
获取URL参数值<span th:text=“${#httpServletRequest.getParameter(‘page’)}”></span>当访问:http://localhost:1105/index?page=5时页面将会得到page对应的值:5
定义变量<div th:with=“curPage={curPage}”></span></h3></div>当访问http://localhost:1105/index?page=5时,页面将显示:当前页码:5,说明用th:with来定义变量,多个用,号隔开,使用范围在当前标签内
自定义标签属性<span th:attr=“myDate={money}”></span>在页面上查看源代码可以看到:<span myMoney=“91.6059494319957” myDate=“2016-31-02”></span>,说明自定义属性用:th:attr,多个属性用,隔开

3.字符串操作

作用实例
判断是否为空{#strings.arrayIsEmpty(nameArr)}、{#strings.setIsEmpty(nameSet)}
是否包含{#strings.containsIgnoreCase(name,‘ez’)}
以xx开始,以xx结束{#strings.endsWith(name,endingFragment)}、{#strings.substring(name,3,5)}、{#strings.substringBefore(name,suffix)}、${#strings.replace(name,‘las’,‘ler’)}
去空格${#strings.trim(str)}
获取长度${#strings.length(str)}
是否相等${#strings.equals(str)}
字符串转int(转成3位){#numbers.formatInteger( num, 3) > #numbers.formatInteger(‘4’,3) }"

使用注意事项

(1)路径要从templates下算起

(2)背景图片的添加

<li th:attr="style='background:url('+ @{/images/login_bg2.jpg} + ');background-size:cover;background-color: #074B7B;background-size: 100%;'">

(3)iframe内嵌页面height值太小导致的页面偏窄

解决办法:删除掉最外层页面的h5声明

(4)引入spring security

要先在maven中引入

 <dependency>
     <groupId>org.thymeleaf.extras</groupId>
     <artifactId>thymeleaf-extras-springsecurity4</artifactId>
 </dependency>

显示用户信息:

<span th:text="${#authentication.principal.username}"> 管理员</span>

根据角色判别,==注意角色名必须要是以“ROLE_”开头,要不然识别不了==

<div th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')}">
    管理员可见
</div>
<div th:if="${#authorization.expression('hasRole(''ROLE_BANK'')')}">
    银行账户可见
</div>

获取url上面的参数,如 /login?error

<div class="layui-form-item" th:if="${#httpServletRequest.getParameter('error')} " style="color: red;text-align: center">账号或密码不正确</div>

(5)模板中标签必须要有结束符的解决办法

在application.yml添加

//使用非严格的html5标签
spring.thymeleaf.mode=LEGACYHTML5

maven 添加依赖

<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.22</version>
</dependency>

(6)拼接俩个参数的类容,其中有null时的处理办法

//在三目运算外加()
th:text="(${item?.description eq null}?'': ${item?.description})  +${item?.phone}"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

未禾

您的支持是我最宝贵的财富!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值