Thymeleaf 提供了丰富的表达式工具类,例如:

#strings:字符串工具类
#dates:时间操作和时间格式化
#numbers:格式化数字对象的方法
#bools:常用的布尔方法


#strings 工具类

◼ 字符串长度(length)
◼ 字符串转换(toString)
◼ 检查字符串是否为空(isEmpty)
◼ 字符串是为空替换操作(defaultString)
◼ 检查字符串中是否包含某个字符串(contains containsIgnoreCase)
◼ 检查字符串是以片段开头还是结尾(startsWith endsWith)
◼ 截取(substring substringAfter substringBefore)
◼ 替换(replace)
◼ 追加(prepend append)
◼ 变更大小写(toUpperCase toLowerCase)
◼ 去空格(trim)
◼ 拆分和组合字符串(arrayJoin arraySplit)

示例:
如果值为 null 或 空串,则 true,否则 false

<p th:text="${#strings.isEmpty(stu.name)}"></p>

如果值为 null 或 空串,则显示默认值张三

<p th:text="${#strings.defaultString(stu.name,'张三')}"></p>

<p th:text="${#strings.length(stu.name)}"></p> <!-- 2 (stu.name='小明') -->
<p th:text="${#strings.contains('abcez','ez')}"></p> <!--true-->
<p th:text="${#strings.startsWith('Donabcez','Don')}"></p> <!--true-->
<p th:text="${#strings.indexOf('abcefg','e')}"></p> <!--3-->
最后一个参数<=总长度

<p th:text="${#strings.substring('abcefg',3,5)}"></p> <!--ef-->

<p th:text="${#strings.replace('aabbccbb','bb','zz')}"></p> <!--aazzcczz-->
<p th:text="${#strings.prepend('88888888','027-')}"></p> <!--027-88888888-->
<p th:text="${#strings.append('abc','123')}"></p> <!--abc123-->
<p th:text="${#strings.toUpperCase('abc')}"></p> <!--ABC-->
<p th:text="${#strings.trim(' abc ')}"></p> <!--abc-->


#dates 工具类

◼ 格式化操作(format)
◼ 获取日期属性操作(day month year hour minute second monthName
dayOfWeek )
◼ 生成日期操作(createNow create createToday)

示例:
后台添加代码:model.addAttribute(“today”,new Date());

<p th:text="${today}"></p>
<p th:text="${#dates.format(today,'yyyy/MM/dd HH:mm:ss')}"></p>
<p th:text="${#dates.year(today)}"></p>
<p th:text="${#dates.month(today)}"></p>
<p th:text="${#dates.monthName(today)}"></p>
<p th:text="${#dates.day(today)}"></p>
<p th:text="${#dates.dayOfWeek(today)}"></p>
<p th:text="${#dates.dayOfWeekName(today)}"></p>
<p th:text="${#dates.hour(today)}"></p>
<p th:text="${#dates.minute(today)}"></p>
<p th:text="${#dates.second(today)}"></p>
<p th:text="${#dates.createNow()}"></p> <!--含有时间-->
<p th:text="${#dates.createToday()}"></p> <!--时间为00:00:00-->
<p th:text="${#dates.create('2021','03','15')}"></p>

#numbers 工具类

◼ 对不够位数的数字进行补0(formatInteger )
◼ 设置千位分隔符(formatInteger)
◼ 精确小数点(formatDecimal )
◼ 设置百分号(formatPercent )
◼ 生成数组(sequence )

示例:
结果:010.13

<p th:text="${#numbers.formatDecimal('10.126',3,2)}"></p>

结果:¥1,000.00

<p th:text="${#numbers.formatCurrency('1000')}"></p>

生成 [0,1,2,3,4] 数组

<div th:each="n:${#numbers.sequence(0,4)}">
	<p th:text="${n}"></p>
</div>

生成 [0,2,4,6,8,10] 数组

<div th:each="num:${#numbers.sequence(0,10,2)}" >
	<p th:text="${num}"></p>
</div>

#bools 工具类

◼ 判断对象是否为 ture 或 false的操作:(isTrue isFalse)
◼ 数字 1 为 ture , 0 为 false;
◼ “on” 为 true, “off” 为 false;
◼ “true” 为 true, "false"为 false;

示例:

<p th:text="${#bools.isTrue(1)}"></p> <!--true-->
<p th:text="${#bools.isTrue('on')}"></p> <!--true-->
<p th:text="${#bools.isTrue('true')}"></p> <!--true-->