Loading

Thymeleaf语法总结 | 笔记分享

Thymeleaf语法总结

一、Thymeleaf介绍

Thymeleaf是Spring boot推荐使用的模版引擎,直接以html显示,前后端可以很好的分离。

 

二、Thymeleaf语法(Thymeleaf3)

在使用Thymeleaf时页面要引入名称空间: xmlns:th="http://www.thymeleaf.org"
 
1、th属性,常用th属性如下:
    1)th:text:文本替换;
<h1 th:text="${session.vel2}"></h1>
    2)th:utext:支持html的文本替换。
    3)th:value:属性赋值  
    4)th:each:遍历循环元素
//每次遍历都会产生th:each所标注的标签以及内部标签 

<tr th:each="user : ${users}">
  <td th:text="${user.name}">Onions</td>
  <td th:text="${user.age}">2.41</td>
</tr>
    5)th:if:判断条件,类似的还有th:unless,th:switch,th:case
<div th:if="true">
    你填的是true
</div> 
//这里引用了一个th:if指令,跟vue中的v-if类似
    6)th:insert:代码块引入,类似的还有th:replace,th:include,常用于公共代码块提取的场景
    7)th:fragment:定义代码块,方便被th:insert引用
    8)th:object:声明变量,一般和*{}一起配合使用,达到偷懒的效果。
<h2 th:object="${user}"> 
  <p>Name: <span th:text="*{name}">Jack</span>.</p> 
  <p>Age: <span th:text="*{age}">21</span>.</p> 
  <p>friend: <span th:text="*{friend.name}">Rose</span>.</p> 
</h2>
    9)th:attr:设置标签属性,多个属性可以用逗号分隔
例子:

前端HTML

<!DOCTYPE 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}" /></p><!--th:text="${thObject.id}"--> <p>TH: <span th:text="*{thName}" /></p><!--${thObject.thName}--> <p>DE: <span th:text="*{desc}" /></p><!--${thObject.desc}--> </div>
</body>
</html>

后台controller:

@Controller
public class ThymeleafController {
 
    @RequestMapping("thymeleaf")
    public String thymeleaf(ModelMap map) {
        map.put("thText", "th:text 设置文本内容 <b>加粗</b>");
        map.put("thUText", "th:utext 设置文本内容 <b>加粗</b>");
        map.put("thValue", "thValue 设置当前元素的value值");
        map.put("thEach", Arrays.asList("th:each", "遍历列表"));
        map.put("thIf", "msg is not null");
        map.put("thObject", new ThObject(1L, "th:object", "用来偷懒的th属性"));
        return "grammar/thymeleaf";
    }
}

 

2、标准表达式语法:

  • ${...} 变量表达式,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标签中,

#{...} 消息表达式

消息表达式一般用于国际化的场景。

@{...} 链接表达式

链接表达式好处
不管是静态资源的引用,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:method="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,containsIgnoreCase等
二、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等
 
 1 <!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head>
 2     <meta charset="UTF-8">
 3     <title>ITDragon Thymeleaf 内置方法</title></head><body>
 4     <h2>ITDragon Thymeleaf 内置方法</h2>
 5     <h3>#strings </h3>
 6     <div th:if="${not #strings.isEmpty(itdragonStr)}" >
 7         <p>Old Str : <span th:text="${itdragonStr}"/></p>
 8         <p>toUpperCase : <span th:text="${#strings.toUpperCase(itdragonStr)}"/></p>
 9         <p>toLowerCase : <span th:text="${#strings.toLowerCase(itdragonStr)}"/></p>
10         <p>equals : <span th:text="${#strings.equals(itdragonStr, 'itdragonblog')}"/></p>
11         <p>equalsIgnoreCase : 
12         <span th:text="${#strings.equalsIgnoreCase(itdragonStr, 'itdragonblog')}"/></p>
13         <p>indexOf : <span th:text="${#strings.indexOf(itdragonStr, 'r')}"/></p>
14         <p>substring : <span th:text="${#strings.substring(itdragonStr, 2, 8)}"/></p>
15         <p>replace : <span th:text="${#strings.replace(itdragonStr, 'it', 'IT')}"/></p>
16         <p>startsWith : <span th:text="${#strings.startsWith(itdragonStr, 'it')}"/></p>
17         <p>contains : <span th:text="${#strings.contains(itdragonStr, 'IT')}"/></p>
18     </div>
19  
20     <h3>#numbers </h3>
21     <div>
22         <p>formatDecimal 整数部分随意,小数点后保留两位,四舍五入: 
23         <span th:text="${#numbers.formatDecimal(itdragonNum, 0, 2)}"/></p>
24         <p>formatDecimal 整数部分保留五位数,小数点后保留两位,四舍五入: 
25         <span th:text="${#numbers.formatDecimal(itdragonNum, 5, 2)}"/></p>
26     </div>
27  
28     <h3>#bools </h3>
29     <div th:if="${#bools.isTrue(itdragonBool)}">
30         <p th:text="${itdragonBool}"></p>
31     </div>
32  
33     <h3>#arrays </h3>
34     <div th:if="${not #arrays.isEmpty(itdragonArray)}">
35         <p>length : <span th:text="${#arrays.length(itdragonArray)}"/></p>
36         <p>contains : <span th:text="${#arrays.contains(itdragonArray, 5)}"/></p>
37         <p>containsAll : <span th:text="${#arrays.containsAll(itdragonArray, itdragonArray)}"/></p>
38     </div>
39     <h3>#lists </h3>
40     <div th:if="${not #lists.isEmpty(itdragonList)}">
41         <p>size : <span th:text="${#lists.size(itdragonList)}"/></p>
42         <p>contains : <span th:text="${#lists.contains(itdragonList, 0)}"/></p>
43         <p>sort : <span th:text="${#lists.sort(itdragonList)}"/></p>
44     </div>
45     <h3>#maps </h3>
46     <div th:if="${not #maps.isEmpty(itdragonMap)}">
47         <p>size : <span th:text="${#maps.size(itdragonMap)}"/></p>
48         <p>containsKey : <span th:text="${#maps.containsKey(itdragonMap, 'thName')}"/></p>
49         <p>containsValue : <span th:text="${#maps.containsValue(itdragonMap, '#maps')}"/></p>
50     </div>
51     <h3>#dates </h3>
52     <div>
53         <p>format : <span th:text="${#dates.format(itdragonDate)}"/></p>
54         <p>custom format : <span th:text="${#dates.format(itdragonDate, 'yyyy-MM-dd HH:mm:ss')}"/></p>
55         <p>day : <span th:text="${#dates.day(itdragonDate)}"/></p>
56         <p>month : <span th:text="${#dates.month(itdragonDate)}"/></p>
57         <p>monthName : <span th:text="${#dates.monthName(itdragonDate)}"/></p>
58         <p>year : <span th:text="${#dates.year(itdragonDate)}"/></p>
59         <p>dayOfWeekName : <span th:text="${#dates.dayOfWeekName(itdragonDate)}"/></p>
60         <p>hour : <span th:text="${#dates.hour(itdragonDate)}"/></p>
61         <p>minute : <span th:text="${#dates.minute(itdragonDate)}"/></p>
62         <p>second : <span th:text="${#dates.second(itdragonDate)}"/></p>
63         <p>createNow : <span th:text="${#dates.createNow()}"/></p>
64     </div></body></html>

 

 
 1 @RequestMapping("varexpressions")public String varexpressions(ModelMap map) {
 2   map.put("itdragonStr", "itdragonBlog");
 3   map.put("itdragonBool", true);
 4   map.put("itdragonArray", new Integer[]{1,2,3,4});
 5   map.put("itdragonList", Arrays.asList(1,3,2,4,0));
 6   Map itdragonMap = new HashMap();
 7   itdragonMap.put("thName", "${#...}");
 8   itdragonMap.put("desc", "变量表达式内置方法");
 9   map.put("itdragonMap", itdragonMap);
10   map.put("itdragonDate", new Date());
11   map.put("itdragonNum", 888.888D);  return "grammar/varexpressions";
12 }

 

 
posted @ 2021-01-02 22:37  黎久桐槐  阅读(573)  评论(0编辑  收藏  举报