Thymeleaf语法
一、th属性
常用th属性解读
html有的属性,Thymeleaf基本都有,而常用的属性大概有七八个。其中th属性执行的优先级从1~8,数字越低优先级越高。
- th:text :设置当前元素的文本内容,相同功能的还有th:utext,两者的区别在于前者不会转义html标签,后者会。优先级不高:order=7
- th:value:设置当前元素的value值,类似修改指定属性的还有th:src,th:href。优先级不高:order=6
- th:each:遍历循环元素,和th:text或th:value一起使用。注意该属性修饰的标签位置,详细往后看。优先级很高:order=2
- th:if:条件判断,类似的还有th:unless,th:switch,th:case。优先级较高:order=3
- th:insert:代码块引入,类似的还有th:replace,th:include,三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景。优先级最高:order=1
- th:fragment:定义代码块,方便被th:insert引用。优先级最低:order=8
- th:object:声明变量,一般和*{}一起配合使用,达到偷懒的效果。优先级一般:order=4
- th:attr:修改任意属性,实际开发中用的较少,因为有丰富的其他th属性帮忙,类似的还有th:attrappend,th:attrprepend。优先级一般:order=5
常用th属性使用
使用Thymeleaf属性需要注意点以下五点:
- 若要使用Thymeleaf语法,首先要声明名称空间: xmlns:th=“http://www.thymeleaf.org”
- 设置文本内容 th:text,设置input的值 th:value,循环输出 th:each,条件判断 th:if,插入代码块 th:insert,定义代码块 th:fragment,声明变量 th:object
- th:each 的用法需要格外注意,打个比方:如果你要循环一个div中的p标签,则th:each属性必须放在p标签上。若你将th:each属性放在div上,则循环的是将整个div。
- 变量表达式中提供了很多的内置方法,该内置方法是用#开头,请不要与#{}消息表达式弄混。
- th:insert,th:replace,th:include 三种插入代码块的效果相似,但区别很大。
<!IDOCTYPE html>
<!--名称空间-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf 语法</title>
</head>
<body>
<h2>ITDragon Thymeleaf 语法</h2>
<!--th:text 设置当前元素的文本内容,常用,优先级不高-->
<p th:text="${thText}" />
<p th:utext"${thUText}" />
<!--th:value设置当前元素的value值,常用,优先级仅比th:text高-->
<input type="text" th:value="${thValue}" />
<!--th:each 遍历列表,常用,优先级很高,仅此于代码块的插入-->
<!--th:each修饰在div上,则div层重复出现,若只想p标签遍历,则修饰在p标签上-->
<div th:each="message : ${thEach}"> <!--遍历整个div-p,不推荐-->
<p th:text="${message}"/>
</div>
<div><!--只遍历p,推荐使用-->
<p th:text="${message}" th:each="message : ${thEach}" />
</div>
<!--th:if条件判断,类似的有th:switch,th:case,优先级仅次于th:each,其中#strings是变量表达式的内置方法-->
<p th:text="${thIf}" th:if="${not strings.isEmpty(thIf)}"></p>
<!--th:insert把代码块插入当前div中,优先级最高,类似的有th:replace, th:include, ~{} : 代码块表达式-->
<div th:insert="~{grammar/common::thCommon}"></div>
<!--th:object声明变量,和{}一起使用-->
<div th:object="${thObject}">
<p>ID:<span th:text="*{id}" /><!--th:text="${thObject.id}"-->
<p>TH:<span th:text="*{thName}" /><!--th:text="${thObject.thName}"-->
<p>DE:<span th:text="*{desc}" /><!--th:text="${thObject.desc}"-->
</div>
</body>
</nemi>
遍历和条件判断结合:
<div th:each="message : ${thEach}">
<p th:text="${message}" th:if="${not strings.isEmpty(message)}" />
<p th:text="${message}" th:if="${message} eq '集合元素3'" />
</div>
thymeleaf:字符串Strings常见的使用方法
- (1)判断是不是为空:null:
<span th:if="${name} != null">不为空</span>
<span th:if="${name1} == null">为空</span>
- (2)判断是不是为空字符串: “”
<span th:if="${#strings.isEmpty(name1)}">空的</span>
- (3)判断是否相同:
<span th:if="${name} eq 'jack'">相同于jack,</span>
<span th:if="${name} eq 'ywj'">相同于ywj,</span>
<span th:if="${name} ne 'jack'">不相同于jack,</span>
- (4)不存在设置默认值:
<span th:text="${name2} ?: '默认值'"></span>
- (5)是否包含(分大小写):
<span th:if="${#strings.contains(name,'ez')}">包ez</span>
<span th:if="${#strings.contains(name,'y')}">包j</span>
- (6)是否包含(不分大小写)
<span th:if="${#strings.containsIgnoreCase(name,'y')}">包j</span>
- 下面的和JAVA的String基本一样
${#strings.startsWith(name,'o')}
${#strings.endsWith(name, 'o')}
${#strings.indexOf(name,frag)}// 下标
${#strings.substring(name,3,5)}// 截取
${#strings.substringAfter(name,prefix)}// 从 prefix之后的一位开始截取到最后,比如 (ywj,y) = wj, 如果是(abccdefg,c) = cdefg//里面有2个c,取的是第一个c
${#strings.substringBefore(name,suffix)}// 同上,不过是往前截取
${#strings.replace(name,'las','ler')}// 替换
${#strings.prepend(str,prefix)}// 拼字字符串在str前面
${#strings.append(str,suffix)}// 和上面相反,接在后面
${#strings.toUpperCase(name)}
${#strings.toLowerCase(name)}
${#strings.trim(str)}
${#strings.length(str)}
${#strings.abbreviate(str,10)}// 我的理解是 str截取0-10位,后面的全部用…这个点代替,注意,最小是3位
二、标准表达式语法
${…} 变量表达式,Variable Expressions
@{…} 链接表达式,Link URL Expressions
#{…} 消息表达式,Message Expressions
~{…} 代码块表达式,Fragment Expressions
*{…} 选择变量表达式,Selection Variable Expressions
变量表达式使用频率最高,其功能也是非常的丰富。所以我们先从简单的代码块表达式开始,然后是消息表达式,再是链接表达式,最后是变量表达式,随带介绍选择变量表达式。
~{…} 代码块表达式
- 支持两种语法结构
推荐:~{templatename::fragmentname}
支持:~{templatename::#id}
templatename:模版名,Thymeleaf会根据模版名解析完整路径:/resources/templates/templatename.html,要注意文件的路径。
fragmentname:片段名,Thymeleaf通过th:fragment声明定义代码块,即:th:fragment=“fragmentname”
id:HTML的id选择器,使用时要在前面加上#号,不支持class选择器。
代码块表达式的使用
代码块表达式需要配合th属性(th:insert,th:replace,th:include)一起使用。
th:insert:将代码块片段整个插入到使用了th:insert的HTML标签中,
th:replace:将代码块片段整个替换使用了th:replace的HTML标签中,
th:include:将代码块片段包含的内容插入到使用了th:include的HTML标签中
<!--th:fragmentname定义代码块标识-->
<footer> th:fragmentname="copy">
© 2021 The Good Thymeleaf Virtual Grocery
</footer>
<!--三种不同的引用方式-->
<div th:insert="footer :: copy" />
<div th:replace="footer :: copy" />
<div th:include="footer :: copy" />
th:insert是在div中插入代码块,即多了一层div
th:replace是将代码块代替当前div,其html结构和之前一致
th:include是将代码块footer的内容插入到div中,即少了一层footer
#{…} 消息表达式
消息表达式一般用于国际化的场景。结构:th:text="#{msg}"
@{…} 链接表达式
-
链接表达式好处
不管是静态资源的引用,form表单的请求,凡是链接都可以用@{…} 。这样可以动态获取项目路径,即便项目名变了,依然可以正常访问
#修改项目名,链接表达式会自动修改路径,避免资源文件找不到
server.context-path=/itdragon -
链接表达式结构
无参:@{/xxx}
有参:@{/xxx(k1=v1,k2=v2)} 对应url结构:xxx?k1=v1&k2=v2
引入本地资源:@{/项目本地的资源路径}
引入外部资源:@{/webjars/资源在jar包中的路径}
<link th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
<link th:href="@{/main/css/itdragon.css}" rel="stylesheet">
<form class="form-login" th:action="@{/user/login}" th:methed="post" >
<a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>
${…}变量表达式
变量表达式有丰富的内置方法,使其更强大,更方便。
- 变量表达式功能
一、可以获取对象的属性和方法
二、可以使用ctx,vars,locale,request,response,session,servletContext内置对象
三、可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法(重点介绍) - 常用的内置对象
一、ctx :上下文对象。
二、vars :上下文变量。
三、locale:上下文的语言环境。
四、request:(仅在web上下文)的 HttpServletRequest 对象。
五、response:(仅在web上下文)的 HttpServletResponse 对象。
六、session:(仅在web上下文)的 HttpSession 对象。
七、servletContext:(仅在web上下文)的 ServletContext 对象
这里以常用的Session举例,用户刊登成功后,会把用户信息放在Session中,Thymeleaf通过内置对象将值从session中获取。
// java 代码将用户名放在session中
session.setAttribute("userInfo", username);
// Thymeleaf 通过内置对象直接获取
th:text="${session.userInfo}"
- 常用的内置方法
一、strings:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsInoreCase等
二、numbers:数值格式化方法,常用的方法有:formatDecimal等
三、bools:布尔方法,常用的方法有:isTrue,isFalse等
四、arrays:数组方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等
五、lists,sets:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等
六、maps:对象方法,常用的方法有:size,isEmpty,containsKey,containsValue等
七、dates:日期方法,常用的方法有:format,year,month,hour,createNow等