Springboot-thymeleaf内置工具用法示例和手册

步骤 1 : 可运行项目

本知识点是建立在 上一个知识点 的基础上进行的改进

首先下载一个简单的可运行项目作为演示:网盘链接https://t.cn/A6AlcauC

下载后解压,比如解压到 E:\project\springboot 目录下

步骤 2 : 修改 TestController

增加了日期对象,并且放在 "now" 这个变量上扔给视图

package com.ryan.springboot.web;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ryan.springboot.pojo.Product;
  
@Controller
public class TestController {
  
    @RequestMapping("/test")
    public String test(Model m) {
        String htmlContent = "<p style='color:red'> 火星红 </p>";
        Product currentProduct =new Product(5,"梦却了无影踪", 666);
        boolean testBoolean = true;
        
        Date now = new Date();
        
        List<Product> ps = new ArrayList<>();
        ps.add(new Product(1,"好像爱这个世界啊", 666));
        ps.add(new Product(2,"疯人院", 666));
        ps.add(new Product(3,"与火星的孩子对话", 666));
        ps.add(new Product(4,"七重人格", 666));
        ps.add(currentProduct);
        ps.add(new Product(6,"神树", 666));
        ps.add(new Product(7,"降临", 666));       
        ps.add(new Product(8,"新世界", 666));       
        m.addAttribute("ps", ps);
        
        m.addAttribute("now", now);
            
        m.addAttribute("htmlContent", htmlContent);
        m.addAttribute("currentProduct", currentProduct);
        m.addAttribute("testBoolean", testBoolean);
        
        return "test";
    }
}

步骤 3 : 修改 test.html

使用 #dates 这个内置工具进行格式化日期

<div class="showing date">
    <h2>格式化日期</h2>
    直接输出日期 ${now}:
    <p th:text="${now}"></p>
    默认格式化 ${#dates.format(now)}:
    <p th:text="${#dates.format(now)}"></p>
    自定义格式化 ${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}:
    <p th:text="${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}"></p>
</div>

完整 test.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<link rel="stylesheet" type="text/css" media="all" href="../../webapp/static/css/style.css" th:href="@{/static/css/style.css}"/>
	<script type="text/javascript" src="../../webapp/static/js/thymeleaf.js" th:src="@{/static/js/thymeleaf.js}"></script>
    
	<style>
		h2{
			text-decoration: underline;
			font-size:0.9em;
			color:gray;
		}
	</style>        
</head>
<body>

<div class="showing date">
    <h2>格式化日期</h2>
    直接输出日期 ${now}:
    <p th:text="${now}"></p>
    默认格式化 ${#dates.format(now)}:
    <p th:text="${#dates.format(now)}"></p>
    自定义格式化 ${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}:
    <p th:text="${#dates.format(now,'yyyy-MM-dd HH:mm:ss')}"></p>
</div>

<div class="showing">
    <h2>遍历</h2>
 
    <table>
        <thead>
            <tr>
                <th>id</th>
                <th>产品名称</th>
                <th>价格</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="p: ${ps}">
                <td th:text="${p.id}"></td>
                <td th:text="${p.name}"></td>
                <td th:text="${p.price}"></td>
            </tr>
        </tbody>
    </table>
</div>
 
<div class="showing">
    <h2>带状态遍历</h2>
    <table>
        <thead>
            <tr>
                <th>index</th>
                <th>id</th>
                <th>产品名称</th>
                <th>价格</th>
            </tr>
        </thead>
        <tbody>
            <tr th:class="${status.even}?'even':'odd'" th:each="p,status: ${ps}">
                <td  th:text="${status.index}"></td>
                <td th:text="${p.id}"></td>
                <td th:text="${p.name}"></td>
                <td th:text="${p.price}"></td>
            </tr>
        </tbody>
    </table>
</div>
 
<div class="showing">
    <h2>遍历 select </h2>
 
    <select size="3">
        <option th:each="p:${ps}" th:value="${p.id}"     th:selected="${p.id==currentProduct.id}"    th:text="${p.name}" ></option>
    </select>
 
</div>
 
<div class="showing">
    <h2>遍历 radio </h2>
 
    <input name="product" type="radio" th:each="p:${ps}" th:value="${p.id}"  th:checked="${p.id==currentProduct.id}"     th:text="${p.name}"  />
 
</div>

<div class="showing">
    <h2>条件判断</h2>
    <p th:if="${testBoolean}" >如果 testBoolean 是 true ,本句话就会显示</p>
    <p th:if="${not testBoolean}" >取反 ,所以如果 testBoolean 是 true ,本句话就不会显示</p>
    <p th:unless="${testBoolean}" >unless 等同于上一句,所以如果 testBoolean 是 true ,本句话就不会显示</p>
    <p th:text="${testBoolean}?'当 testBoolean 为真的时候,显示本句话,这是用三相表达式做的':''" ></p>
</div>

<div class="showing">
	<h2>显示 转义和非转义的 html 文本</h2>
	<p th:text="${htmlContent}" ></p>
	<p th:utext="${htmlContent}" ></p>
</div>

<div class="showing">
	<h2>显示对象以及对象属性</h2>
	<p th:text="${currentProduct}" ></p>
	<p th:text="${currentProduct.name}" ></p>
	<p th:text="${currentProduct.getName()}" ></p>
</div>

<div class="showing" th:object="${currentProduct}">
	<h2>*{}方式显示属性</h2>
	<p th:text="*{name}" ></p>
</div>

<div class="showing">
	<h2>算数运算</h2>
	<p th:text="${currentProduct.price+222}" ></p>
</div>

<div class="showing">
    <div th:replace="include::footer1" ></div>
    <div th:replace="include::footer2(2020,2200)" ></div>
</div>

</body>    
</html>

步骤 4 : 测试

重新运行 Application.java, 然后测试

http://127.0.0.1:8080/thymeleaf/test

显示效果:

步骤 5 : thymeleaf 内置工具

像 #date 这样的 thymeleaf 内置工具有很多种,一共有如下16种。

内置工具 说明
IDs 处理可能重复的id属性的方法
Execution Info 获取页面模板的处理信息
Messages 在变量表达式中获取外部消息的方法,与使用#{...}语法获取的方法相同
URIs/URLs 转义部分URL / URI的方法
Conversions 用于执行已配置的转换服务的方法
Dates 时间操作和时间格式化等
Calendars 用于更复杂时间的格式化
Numbers 格式化数字对象的方法
Strings 字符串工具类
Objects 一般对象类,通常用来判断非空
Booleans 常用的布尔方法
Arrays 数组工具类
Lists List 工具类
Sets Set 工具类
Maps 常用Map方法
Aggregates 在数组或集合上创建聚合的方法

并不是每一种都用得到,所以这里把他们的用法手册列出来了,将来用到的时候再来查看就行了。

步骤 6 : IDs

${#ids.seq('someId')}
${#ids.next('someId')}
$

步骤 7 : Execution Info

${#execInfo.templateName}
${#execInfo.templateMode}
${#execInfo.processedTemplateName}
${#execInfo.processedTemplateMode}
${#execInfo.templateNames}
${#execInfo.templateModes}
$

步骤 8 : Messages

${#messages.msg('msgKey')}
${#messages.msg('msgKey', param1)}
${#messages.msg('msgKey', param1, param2)}
${#messages.msg('msgKey', param1, param2, param3)}
${#messages.msgWithParams('msgKey', new Object[] {param1, param2, param3, param4})}
${#messages.arrayMsg(messageKeyArray)}
${#messages.listMsg(messageKeyList)}
${#messages.setMsg(messageKeySet)}
${#messages.msgOrNull('msgKey')}
${#messages.msgOrNull('msgKey', param1)}
${#messages.msgOrNull('msgKey', param1, param2)}
${#messages.msgOrNull('msgKey', param1, param2, param3)}
${#messages.msgOrNullWithParams('msgKey', new Object[] {param1, param2, param3, param4})}
${#messages.arrayMsgOrNull(messageKeyArray)}
${#messages.listMsgOrNull(messageKeyList)}
$

步骤 9 : URIs/URLs

${#uris.escapePath(uri)}
${#uris.escapePath(uri, encoding)}
${#uris.unescapePath(uri)}
${#uris.unescapePath(uri, encoding)}
${#uris.escapePathSegment(uri)}
${#uris.escapePathSegment(uri, encoding)}
${#uris.unescapePathSegment(uri)}
${#uris.unescapePathSegment(uri, encoding)}
${#uris.escapeFragmentId(uri)}
${#uris.escapeFragmentId(uri, encoding)}
${#uris.unescapeFragmentId(uri)}
${#uris.unescapeFragmentId(uri, encoding)}
${#uris.escapeQueryParam(uri)}
${#uris.escapeQueryParam(uri, encoding)}
${#uris.unescapeQueryParam(uri)}
$

步骤 10 : Conversions

${#conversions.convert(object, 'java.util.TimeZone')}
$

步骤 11 : Dates

${#dates.format(date)}
${#dates.arrayFormat(datesArray)}
${#dates.listFormat(datesList)}
${#dates.setFormat(datesSet)}
${#dates.formatISO(date)}
${#dates.arrayFormatISO(datesArray)}
${#dates.listFormatISO(datesList)}
${#dates.setFormatISO(datesSet)}
${#dates.format(date, 'dd/MMM/yyyy HH:mm')}
${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}
${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}
${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}
${#dates.day(date)}
${#dates.month(date)}
${#dates.monthName(date)}
${#dates.monthNameShort(date)}
${#dates.year(date)}
${#dates.dayOfWeek(date)}
${#dates.dayOfWeekName(date)}
${#dates.dayOfWeekNameShort(date)}
${#dates.hour(date)}
${#dates.minute(date)}
${#dates.second(date)}
${#dates.millisecond(date)}
${#dates.create(year,month,day)}
${#dates.create(year,month,day,hour,minute)}
${#dates.create(year,month,day,hour,minute,second)}
${#dates.create(year,month,day,hour,minute,second,millisecond)}
${#dates.createNow()}
${#dates.createNowForTimeZone()}
${#dates.createToday()}
$

步骤 12 : Calendars

${#calendars.format(cal)}
${#calendars.arrayFormat(calArray)}
${#calendars.listFormat(calList)}
${#calendars.setFormat(calSet)}
${#calendars.formatISO(cal)}
${#calendars.arrayFormatISO(calArray)}
${#calendars.listFormatISO(calList)}
${#calendars.setFormatISO(calSet)}
${#calendars.format(cal, 'dd/MMM/yyyy HH:mm')}
${#calendars.arrayFormat(calArray, 'dd/MMM/yyyy HH:mm')}
${#calendars.listFormat(calList, 'dd/MMM/yyyy HH:mm')}
${#calendars.setFormat(calSet, 'dd/MMM/yyyy HH:mm')}
${#calendars.day(date)}
${#calendars.month(date)}
${#calendars.monthName(date)}
${#calendars.monthNameShort(date)}
${#calendars.year(date)}
${#calendars.dayOfWeek(date)}
${#calendars.dayOfWeekName(date)}
${#calendars.dayOfWeekNameShort(date)}
${#calendars.hour(date)}
${#calendars.minute(date)}
${#calendars.second(date)}
${#calendars.millisecond(date)}
${#calendars.create(year,month,day)}
${#calendars.create(year,month,day,hour,minute)}
${#calendars.create(year,month,day,hour,minute,second)}
${#calendars.create(year,month,day,hour,minute,second,millisecond)}
${#calendars.createForTimeZone(year,month,day,timeZone)}
${#calendars.createForTimeZone(year,month,day,hour,minute,timeZone)}
${#calendars.createForTimeZone(year,month,day,hour,minute,second,timeZone)}
${#calendars.createForTimeZone(year,month,day,hour,minute,second,millisecond,timeZone)}
${#calendars.createNow()}
${#calendars.createNowForTimeZone()}
${#calendars.createToday()}
$

步骤 13 : Numbers

${#numbers.formatInteger(num,3)}
${#numbers.arrayFormatInteger(numArray,3)}
${#numbers.listFormatInteger(numList,3)}
${#numbers.setFormatInteger(numSet,3)}
${#numbers.formatInteger(num,3,'POINT')}
${#numbers.arrayFormatInteger(numArray,3,'POINT')}
${#numbers.listFormatInteger(numList,3,'POINT')}
${#numbers.setFormatInteger(numSet,3,'POINT')}
${#numbers.formatDecimal(num,3,2)}
${#numbers.arrayFormatDecimal(numArray,3,2)}
${#numbers.listFormatDecimal(numList,3,2)}
${#numbers.setFormatDecimal(numSet,3,2)}
${#numbers.formatDecimal(num,3,2,'COMMA')}
${#numbers.arrayFormatDecimal(numArray,3,2,'COMMA')}
${#numbers.listFormatDecimal(numList,3,2,'COMMA')}
${#numbers.setFormatDecimal(numSet,3,2,'COMMA')}
${#numbers.formatDecimal(num,3,'POINT',2,'COMMA')}
${#numbers.arrayFormatDecimal(numArray,3,'POINT',2,'COMMA')}
${#numbers.listFormatDecimal(numList,3,'POINT',2,'COMMA')}
${#numbers.setFormatDecimal(numSet,3,'POINT',2,'COMMA')}
${#numbers.formatCurrency(num)}
${#numbers.arrayFormatCurrency(numArray)}
${#numbers.listFormatCurrency(numList)}
${#numbers.setFormatCurrency(numSet)}
${#numbers.formatPercent(num)}
${#numbers.arrayFormatPercent(numArray)}
${#numbers.listFormatPercent(numList)}
${#numbers.setFormatPercent(numSet)}
${#numbers.formatPercent(num, 3, 2)}
${#numbers.arrayFormatPercent(numArray, 3, 2)}
${#numbers.listFormatPercent(numList, 3, 2)}
${#numbers.setFormatPercent(numSet, 3, 2)}
${#numbers.sequence(from,to)}
$

步骤 14 : Strings

${#strings.toString(obj)}
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)}
${#strings.defaultString(text,default)}
${#strings.arrayDefaultString(textArr,default)}
${#strings.listDefaultString(textList,default)}
${#strings.setDefaultString(textSet,default)}
${#strings.contains(name,'ez')}
${#strings.containsIgnoreCase(name,'ez')}
${#strings.startsWith(name,'Don')}
${#strings.endsWith(name,endingFragment)}
${#strings.indexOf(name,frag)}
${#strings.substring(name,3,5)}
${#strings.substringAfter(name,prefix)}
${#strings.substringBefore(name,suffix)}
${#strings.replace(name,'las','ler')}
${#strings.prepend(str,prefix)}
${#strings.append(str,suffix)}
${#strings.toUpperCase(name)}
${#strings.toLowerCase(name)}
${#strings.arrayJoin(namesArray,',')}
${#strings.listJoin(namesList,',')}
${#strings.setJoin(namesSet,',')}
${#strings.arraySplit(namesStr,',')}
${#strings.listSplit(namesStr,',')}
${#strings.setSplit(namesStr,',')}
${#strings.trim(str)}
${#strings.length(str)}
${#strings.abbreviate(str,10)}
${#strings.capitalize(str)}
${#strings.unCapitalize(str)}
${#strings.capitalizeWords(str)}
${#strings.capitalizeWords(str,delimiters)}
${#strings.escapeXml(str)}
${#strings.escapeJava(str)}
${#strings.escapeJavaScript(str)}
${#strings.unescapeJava(str)}
${#strings.unescapeJavaScript(str)}
${#strings.equals(first, second)}
${#strings.equalsIgnoreCase(first, second)}
${#strings.concat(values...)}
${#strings.concatReplaceNulls(nullValue, values...)}
$

步骤 15 : Objects

${#objects.nullSafe(obj,default)}
${#objects.arrayNullSafe(objArray,default)}
${#objects.listNullSafe(objList,default)}
$

步骤 16 : Booleans

${#bools.isTrue(obj)}
${#bools.arrayIsTrue(objArray)}
${#bools.listIsTrue(objList)}
${#bools.setIsTrue(objSet)}
${#bools.isFalse(cond)}
${#bools.arrayIsFalse(condArray)}
${#bools.listIsFalse(condList)}
${#bools.setIsFalse(condSet)}
${#bools.arrayAnd(condArray)}
${#bools.listAnd(condList)}
${#bools.setAnd(condSet)}
${#bools.arrayOr(condArray)}
${#bools.listOr(condList)}
$

步骤 17 : Arrays

${#arrays.toArray(object)}
${#arrays.toStringArray(object)}
${#arrays.toIntegerArray(object)}
${#arrays.toLongArray(object)}
${#arrays.toDoubleArray(object)}
${#arrays.toFloatArray(object)}
${#arrays.toBooleanArray(object)}
${#arrays.length(array)}
${#arrays.isEmpty(array)}
${#arrays.contains(array, element)}
$

步骤 18 : Lists

${#lists.toList(object)}
${#lists.size(list)}
${#lists.isEmpty(list)}
${#lists.contains(list, element)}
${#lists.containsAll(list, elements)}
${#lists.sort(list)}
${#lists.sort(list, comparator)}
$

步骤 19 : Sets

${#sets.size(set)}
${#sets.isEmpty(set)}
${#sets.contains(set, element)}
$

步骤 20 : Maps

${#maps.size(map)}
${#maps.isEmpty(map)}
${#maps.containsKey(map, key)}
${#maps.containsAllKeys(map, keys)}
${#maps.containsValue(map, value)}
$

步骤 21 : Aggregates

${#aggregates.sum(array)}
${#aggregates.sum(collection)}
${#aggregates.avg(array)}
$

更多关于 Springboot_thymeleaf_内置工具 详细内容,点击学习: https://t.cn/A6A33dlG

posted @ 2020-05-05 10:31  梦却了无影踪  阅读(563)  评论(0编辑  收藏  举报