Thymeleaf 随笔文档
Thymeleaf 非常强调自然模板化——允许模板成为工作原型,而其他两个模板不允许这样做——它的语法试图(可以说)更干净,更符合当前 web开发的趋势。另外,从架构的角度来看,Velocity 和 FreeMarker 都是顺序文本处理器,而 Thymeleaf 是基于标记解析技术的。这允许 Thymeleaf 利用特定于基于标记的环境的有趣特性,特别是web。
SpringBoot使用Thymeleaf 操作步骤
第一步是引入Thymeleaf starter依赖
具体代码如下:
<!-- thymeleaf 相关依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
第二步 application.properties 添加 Thymeleaf 相关配置
具体配置如下:
server.port=8090 server.servlet.context-path=/sbe #关闭 Thymeleaf 的缓存开发过程中无需重启 spring.thymeleaf.cache = false #设置thymeleaf页面的编码 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.mode=HTML5 #设置thymeleaf页面的后缀 spring.thymeleaf.suffix=.html #设置thymeleaf页面的存储路径 spring.thymeleaf.prefix=classpath:/templates/
第三步是编写Controller
访问 Thymeleaf 页面 Controller
@Controller @RequestMapping("/hello") public class ThymeleafHelloWrodController { @RequestMapping("/thymeleaf") public String helloThymeleaf(Model model){ model.addAttribute("hello","hello Thymeleaf!"); return "hello/index"; } }
Thymeleaf 标签语法使用
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <p th:text="${hello}">hello</p> </body> </html>
session获取
后端代码:
//创建session对象 HttpSession session = request.getSession(true); session.setAttribute("USER_INFO",userInfo);//把用户数据保存到session对象中
前端代码:
<span class="x-red" th:text="${session.USER_INFO.uName}"/>
servletContext获取
后端代码:
servletContext.setAttribute("COUNT",val);
前端代码:
<cite th:text="${#servletContext.getAttribute('COUNT')}">99</cite>
th:text
进行文本替换 不会解析html
<p th:text="text标签: + ${msg}"></p>
h:utext
进行文本替换 会解析html
<p th:utext="utext标签: + ${msg}"></p>
这里的符号自己输入 貌似报渲染错误,我目前也不知道啥原因,所以贴一端能用的符号
'!', '!=', '%', '&#', '&&', '>', '<', '(', '*', '+', '+=', ',', '-', '.', '/', <, <=, <Literal>, '=', '==', '>', '>=', '?', '?.', '?:', IDENTIFIER, STRING_IDENTIFIER, and, div, empty, eq, ge, gt, le, lt, mod, ne, not, or, '|' or '||' expected, got ':'
拼接
:字符串通过 + 或者 | 进行拼接
@RequestMapping("/th") public String th(Model model){ model.addAttribute("a",1); model.addAttribute("b",2); return "/course/th"; }
<p th:text="${a}+${b}"></p>
结果: <p>3</p>
<p th:text="|${a} ${b}|"></p>
结果: <p>1 2</p>
<p th:text="${a} > ${b}"></p>
结果: <p>false</p>
@RequestMapping("/th") public String th(Model model){ model.addAttribute("flag",true); return "/course/th"; }
<p th:text="!${flag}"></p>
结果: <p>false</p>
*{...}和 ${...}表达式
正常情况下 *{...} 和 ${...}是一样的,但是 *{...} 一般和 th:object 进行一起使用来完成对象属性的简写。
代码演示:
@RequestMapping("/th") public String th(Model model){ User user = new User("ljk",18); model.addAttribute("user",user); return "/course/th"; }
使用 ${...}操作
模版代码:
<p th:text="${user.name}"></p> <p th:text="${user.age}"></p>
<p>ljk</p><p>18</p>
*使用 {...}操作
模版代码:
<p th:text="*{user.name}"></p> <p th:text="*{user.age}"></p>
结果页面:<p>ljk</p><p>18</p>*
使用 {...}特有操作
模版代码:
<div th:object="${user}" > <p th:text="*{name}"></p> <p th:text="*{age}"></p> </div>
结果页面:<p>ljk</p><p>18</p>
~{...}片段表达式
这个一般和模版布局的语法一起使用,具体使用方式请看下面模版布局的教程。
@{...}链接网址表达式
一般和 th:href、th:src进行结合使用,用于显示Web 应用中的URL链接。通过@{...}表达式Thymeleaf 可以帮助我们拼接上web应用访问的全路径,同时我们可以通过()进行参数的拼接
代码演示:
<img th:src="@{/images/gtvglogo.png}" />
结果:<img src="/sbe/images/gtvglogo.png">
<a th:href="@{/product/comments(prodId=${prod.id})}" >查看</a>
结果:<a href="/sbe/product/comments?prodId=2">查看</a>
<a th:href="@{/product/comments(prodId=${prod.id},prodId2=${prod.id})}" >查看</a>
结果:<a href="/sbe/product/comments?prodId=2&prodId2=2">查看</a>
条件判断 th:if/th:unless
th:if 当条件为true则显示。
th:unless 当条件为false 则显示。
代码演示:
java代码:
@RequestMapping("/thif") public String thif(Model model){ model.addAttribute("flag",true); return "/course/thif"; }
<p th:if="${flag}">if判断</p>
结果:<p>if判断</p>
<p th:unless="!${flag}">unless 判断</p>
结果:<p>unless 判断</p>
switch
th:switch
我们可以通过switch来完成类似的条件表达式的操作。
代码演示:
java代码:
@RequestMapping("/thswitch") public String thswitch(Model model){ User user = new User("ljk",23); model.addAttribute("user",user); return "/course/thswitch"; }
<div th:switch="${user.name}"> <p th:case="'ljk'">User is ljk</p> <p th:case="ljk1">User is ljk1</p> </div>
结果:
<div><p> User is ljk</p></div>
for循环
th:each
遍历集合
代码演示:
java代码:
@RequestMapping("/theach") public String theach(Model model){ List<User> userList = new ArrayList<User>(); User user1 = new User("ljk",18); User user2 = new User("ljk2",19); User user3 = new User("ljk3",20); User user4 = new User("lj4",21); userList.add(user1); userList.add(user2); userList.add(user3); userList.add(user4); model.addAttribute("userList",userList); List<String> strList = new ArrayList<String>(); strList.add("ljk"); strList.add("ljk2"); strList.add("ljk3"); strList.add("lj4"); model.addAttribute("strList",strList); return "/course/theach"; }
<table> <thead> <tr> <th>用户名称</th> <th>用户年龄</th> </tr> </thead> <tbody> <tr th:each="user : ${userList}" th:class="${userStat.odd}? 'odd'"> <td th:text="${user.name}">Onions</td> <td th:text="${user.age}">2.41</td> </tr> </tbody> </table> ---------------------------------------------------------------------- <table> <thead> <tr> <th>用户名称</th> </tr> </thead> <tbody> <tr th:each="str : ${strList}" th:class="${strStat.odd}? 'odd'"> <td th:text="${str}">Onions</td> </tr> </tbody> </table>
结果:
我们可以通过便利的变量名+Stat 来获取索引 是否是第一个或最后一个等。
便利的变量名+Stat称作状态变量,其属性有:
- index:当前迭代对象的迭代索引,从0开始,这是索引属性;
- count:当前迭代对象的迭代索引,从1开始,这个是统计属性;
- size:迭代变量元素的总量,这是被迭代对象的大小属性;
- current:当前迭代变量;
- even/odd:布尔值,当前循环是否是偶数/奇数(从0开始计算);
- first:布尔值,当前循环是否是第一个;
- last:布尔值,当前循环是否是最后一个
th:href
<a href="../home.html" th:href="@{/}">返回首页</a>
结果:<a href="/sbe/">返回首页</a>
th:class
<p th:class=" 'even'? 'even' : 'odd'" th:text=" 'even'? 'even' : 'odd'"></p>
结果:<p class="even">even</p>
th:attr
<img th:attr="src=@{/images/gtvglogo.png}" />
结果:<img src="/sbe/images/gtvglogo.png">
th:action
用于声明html from标签中action属性信息。
<form action="subscribe.html" th:action="@{/subscribe}"> <input type="text" name="name" value="abc"/> </form>
结果:
<form action="/sbe/subscribe">
<input type="text" name="name" value="abc">
</form>
th:value
用于声明html中value属性信息。
<input type="text" th:value="${name}" />
结果:
<input type="text" value="ljk">
th:id
用于声明htm id属性信息。
<p th:id="${id}"></p>
结果:<p id="123"></p>
th:onclick
用于声明htm 中的onclick事件。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> function showUserInfo(){ alert("i am zhuoqianmingyue!") } </script> </head> <body> <p th:onclick="'showUserInfo()'">点我</p> </body> </html>
th:selected
用于声明htm 中的selected属性信息。
<select> <option name="sex"></option> <option th:selected="1 == ${sex}">男</option> <option th:selected="0 == ${sex}">女</option> </select>
th:src
用于声明htm 中的img中src属性信息。
<img title="GTVG logo" th:src="@{/images/gtvglogo.png}" />
结果:<img title="GTVG logo" src="/sbe/images/gtvglogo.png">
th:style
用于声明htm中的标签 css的样式信息。
<p th:style="'display:' + @{(${isShow} ? 'none' : 'block')} + ''"></p>
结果:<p style="display:none"></p>
th:with
用于thymeleaf 模版页面中局部变量定义的使用。
<p th:with="df='dd/MMM/yyyy HH:mm'"> Today is: <span th:text="${#dates.format(today,df)}">13 February 2011</span> </p>
结果:<span>02/六月/2019 06:52</span>
<div th:with="firstEle=${users[0]}"> <p> users集合 第一个用户的名称是: <span th:text="${firstEle.name}"></span>. </p> </div>
还有一种用法是在模版布局中带参数的引用片段中使用方式如下:
<div th:replace="::frag" th:with="onevar=${value1},twovar=${value2}">
Elvis运算符
<p>Age: <span th:text="${age}?: '年龄为nll'"></span></p>
三元表达式
我们可以在thymeleaf 的语法中使用三元表达式 具体使用方法是在th:x 中通过 表达式?1选项:2选项。
<p th:class=" 'even'? 'even' : 'odd'" th:text=" 'even'? 'even' : 'odd'"></p>
<p th:value="${name eq 'ljk' ? '帅哥':'丑男'}" th:text="${name eq 'ljk' ? '帅哥':'丑男'}"></p>
条件表达式操作字符:
gt:great than(大于)
ge:great equal(大于等于)
eq:equal(等于)
lt:less than(小于)
le:less equal(小于等于)
ne:not equal(不等于)
内联
开启内联
如何使用内连操作
我们可以通过 在父标签声明 th:inline="text" 来开启内联操作。当然如果想整个页面使用可以直接声明在body上即可。具体使用方式如下面代码所示。
模版页面:
<div th:inline="text"> <p>Hello, [[${user.name}]]!</p> </div>
结果:
<div> <p>Hello,zhuoqianmingyue!</p> </div>
这样的操作和使用th:text是等同的。
<div> <p th:text="Hello,+${user.name}"></p> </div>
[[...]]对应于th:text,[(...)]对应于th:utext
禁用内联操作
这我们可以通过在父标签或者本标签上声明th:inline="none"来禁用内联的操作,如下面代码所示:
模版页面:
<p th:inline="none">A double array looks like this: [[1, 2, 3], [4, 5]]!</p>
结果:
<p>A double array looks like this: [[1, 2, 3], [4, 5]]!</p>
JavaScript内联
如果我们想在JavaScript 中使用内联操作,需要在 script 标签上声明 th:inline="javascript" 然后我们就可以 script 标签中使用内联操作了。具体使用方式如下面代码所示:
模版页面:
<script th:inline="javascript"> var username = [[${user.name}]]; </script>
结果:
<script th:inline="javascript"> var username = "zhuoqianmingyue"; </script>
CSS内联
我们可以通过在 style 标签上声明 th:inline="css" 来开启在css中使用内联的操作,具体操作方式如下:
<style th:inline="css"> ... </style>
例如,假设我们将两个变量设置为两个不同的String值:
classname = 'main elems'
align = 'center'
我们可以像以下一样使用它们:
<style th:inline="css"> .[[${classname}]] { text-align: [[${align}]]; } </style>
结果:
<style th:inline="css"> .main\ elems { text-align: center; } </style>
模板布局
定义引用片段代码
SpringBoot2.0 使用模版模版布局需要先引入 thymeleaf的 thymeleaf-layout-dialect依赖
<dependency> <groupId>nz.net.ultraq.thymeleaf</groupId> <artifactId>thymeleaf-layout-dialect</artifactId> </dependency>
定义footer.html页面 该页面就是我们的引用片段代码
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div th:fragment="copy"> © 2011 The Good Thymes Virtual Grocery </div> </body> </html>
我们可以通过 th:fragment 来定义引用片段,然后可以在其他页面进行引用。
定义引用页面 index.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div th:insert="~{footer :: copy}"></div> </body> </html>
通过 th:insert 和 ~{...}片段引用表达式 进行引入footer.html中定义的片段
结果:
<div> <div> © 2011 The Good Thymes Virtual Grocery </div> </div>
如下面的代码2种方式的写法是一致的。如果你觉得~{footer :: copy}写法比较麻烦可以采用简写的方式footer :: copy。
<div th:insert="footer :: copy"></div> <div th:insert="~{footer :: copy}"></div>
通过id属性来声明片段
我们可以通过 th:fragment 来定义引用片段,但是我们也可以通过在引用片段代码上声明id属性的方式进行片段的引用,具体操作方式如下:
定义引用片段代码模版页面 footer.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="copy-section" > © 2011 The Good Thymes Virtual Grocery </div> </body> </html>
引用引用片段的模版页面:index.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div th:insert="~{footer :: #copy-section}"></div> </body> </html>
结果页面:
<div> <div id="copy-section"> © 2011 The Good Thymes Virtual Grocery </div> </div>
format操作
<span th:text="${#dates.format(date)}">4564546</span>
结果:
<span>2019年5月30日 上午10时03分24秒 </span>
<span th:text="${#dates.format(date, 'dd/MMM/yyyy HH:mm')}">4564546</span>
结果:
<span>30/五月/2019 10:03 </span>
Date[] datesArray = new Date[2]; datesArray[0] = date; datesArray[1] = date2;
<p th:text="${#dates.format(datesArray, 'yyyy-MM-dd HH:mm')}"></p>
结果:<p>2019-05-30 10:03</p>
List<Date> datesList = new ArrayList<Date>(); datesList.add(date); datesList.add(date2); model.addAttribute("datesList",datesList);
<p th:text="${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}"></p>
结果: <p>[30/五月/2019 10:03, 30/五月/2018 00:00]</p>
获取日期属性操作
java代码:
Date date = new Date();
<p th:text="${#dates.day(date)} "></p> <p>30</p> <p th:text="${#dates.month(date)}"></p> <p>5</p> <p th:text="${#dates.monthName(date)}"></p> <p>五月</p> <p th:text="${#dates.year(date)}"></p> <p>2019</p> <p th:text="${#dates.dayOfWeek(date)}"></p> <p>5</p> <p th:text="${#dates.dayOfWeekName(date)}"></p> <p>星期四</p> <p th:text="${#dates.dayOfWeekNameShort(date)}"></p> <p>星期四</p> <p th:text="${#dates.hour(date)}"></p> <p>10</p> <p th:text="${#dates.minute(date)}"></p> <p>10</p> <p th:text="${#dates.second(date)}"></p> <p>45</p> <p th:text="${#dates.millisecond(date)} "></p> <p>853</p>
生成日期操作
<p th:text="${#dates.createNow()}"></p> <p>Thu May 30 10:15:55 CST 2019</p> <p th:text="${#dates.format(#dates.createNow())}"></p> <p>2019年5月30日 上午10时15分55秒</p> <p th:text="${#dates.create('2019','05','30')}"></p> <p>Thu May 30 00:00:00 CST 2019</p> <p th:text="${#dates.create('2019','05','31','10','18')}"></p> <p>Fri May 31 10:18:00 CST 2019</p> <p th:text="${#dates.create('2019','05','30','10','18','34')}"></p> <p>Thu May 30 10:18:34 CST 2019</p> <p th:text="${#dates.createToday()}"></p> <p>Thu May 30 00:00:00 CST 2019</p>
#numbers
处理数字数据的转换
。包括:
- 对不够位数的数字进行补0(formatInteger )
- 设置千位分隔符(formatInteger)
- 精确小数点(formatDecimal )
- 设置百分号(formatPercent )
- 生成数组(sequence )
<p th:text="${#numbers.formatInteger('123',4)}"></p> <p>0123</p> <p th:text="${#numbers.formatInteger('123',3)}"></p> <p>123</p> <p th:text="${#numbers.formatInteger('123',2)}"></p> <p>123</p> <p th:text="${#numbers.listFormatInteger(numList,3)}"></p> <p>[001, 012, 013]</p>
千位分隔符操作
<p th:text="${#numbers.formatInteger('1000',2,'POINT')}"></p> <p>1.000</p> <p th:text="${#numbers.formatInteger('1000',6,'POINT')}"></p> <p>001.000</p> <p th:text="${#numbers.formatInteger('1000',7,'POINT')}"></p> <p>0.001.000</p> <p th:text="${#numbers.formatInteger('1000',2,'COMMA')}"></p> <p>1,000</p> <p th:text="${#numbers.formatInteger('1000',2,'WHITESPACE')}"></p> <p>1 000</p> <p th:text="${#numbers.formatInteger('1000',2,'NONE')}"></p> <p>1000</p> <p th:text="${#numbers.formatInteger('1000',2,'DEFAULT')}"></p> <p>1,000</p>
精确小数点操作
<p th:text="${#numbers.formatDecimal('10.123',3,2)}"></p> <p>010.12</p> <p th:text="${#numbers.formatDecimal('1000.123',5,'POINT',2,'COMMA')}"></p> <p>01.000,12</p> <p th:text="${#numbers.formatCurrency('1000')}"></p> <p>¥1,000.00</p>
百分比操作
<p th:text="${#numbers.formatPercent('0.2',2, 4)}"></p> <p>20.0000%</p> <p th:text="${#numbers.formatPercent('0.2',3, 2)}"></p> <p>020.00%</p>
生成数组操作
<div th:each="num : ${#numbers.sequence(0,4)}" > <p th:text="${num}"></p> </div>
<div><p>0</p></div>
<div><p>1</p></div>
<div><p>2</p></div>
<div><p>3</p></div>
<div><p>4</p></div>
<div th:each="num : ${#numbers.sequence(0,4,1)}" > <p th:text="${num}"></p> </div>
<div><p>0</p></div>
<div><p>1</p></div>
<div><p>2</p></div>
<div><p>3</p></div>
<div><p>4</p></div>
<div th:each="num : ${#numbers.sequence(0,10,2)}" > <p th:text="${num}"></p> </div>
<div><p>0</p></div>
<div><p>2</p></div>
<div><p>4</p></div>
#strings
处理String的相关操作,包括:
- 字符串转换(toString)
- 检查字符串是否为空(isEmpty)
- 字符串是为空替换操作(defaultString)
- 检查字符串中是否包含某个字符串(contains containsIgnoreCase)
- 检查字符串是以片段开头还是结尾(startsWith endsWith)
- 截取(substring substringAfter)
- 替换(replace)
- 追加(prepend append)
- 变更大小写(toUpperCase toLowerCase)
- 拆分和组合字符串(arrayJoin arraySplit)
- 去空格(trim)
- 缩写文本(abbreviate)
- 字符串连接(concat)
<p th:text="${#strings.toString(object)}"></p>
结果
<p>123</p>
<p th:text="${#strings.toString(numList)}"></p>
结果
<p>[1, 12, 13]</p>
isEmpty操作
<p th:text="${#strings.isEmpty(name)}"></p>
结果(判断是否为null)
<p>true</p>
<p th:text="${#strings.listIsEmpty(nameList)}"></p>
结果(遍历判断每个值是否为null)
<p>[false, true]</p>
contains操作
<p th:text="${#strings.contains('abcez','ez')}"></p> <p>true</p> <p th:text="${#strings.containsIgnoreCase('abcEZ','ez')}"></p> <p>true</p>
startsWith endsWith 操作
<p th:text="${#strings.startsWith('Donabcez','Don')}"></p> <p th:text="${#strings.endsWith('Donabcezn','n')}"></p>
结果为 true
indexOf操作
<p th:text="${#strings.indexOf('abcefg','e')}"></p>
结果:
<p>3</p>
substring操作
<p th:text="${#strings.substring('abcefg',3,5)}"></p>
结果:<p>ef</p>
replace操作
<p th:text="${#strings.replace('lasabce','las','ler')}"></p>
结果:<p>lerabce</p>
prepend操作
<p th:text="${#strings.prepend('abc','012')}"></p>
结果:<p>012abc</p>
append操作
<p th:text="${#strings.append('abc','456')}"></p>
结果:<p>abc456</p>
toUpperCase操作
<p th:text="${#strings.toUpperCase('abc')}"></p>
结果:ABC
toLowerCase操作
<p th:text="${#strings.toLowerCase('ABC')}"></p>
结果:abc
length操作
<p th:text="${#strings.length('abc')}"></p>
结果:3
isTrue操作
<p th:text="${#bools.isTrue(true)} "></p>
转载来源: https://www.cnblogs.com/jerry126/p/11531310.html