26.THYMELEAF 内置工具用法示例和手册

可以看到如图所示的日期信息被格式化后的结果。
日期格式化的方式,就是借助了 thymeleaf 内置工具实现的。
先运行,看到效果,再学习
 步骤 3 : 

模仿和排错

在确保可运行项目能够正确无误地运行之后,再严格照着教程的步骤,对代码模仿一遍。 
模仿过程难免代码有出入,导致无法得到期望的运行结果,此时此刻通过比较正确答案 ( 可运行项目 ) 和自己的代码,来定位问题所在。 
采用这种方式,学习有效果,排错有效率,可以较为明显地提升学习速度,跨过学习路上的各个槛。 

推荐使用diffmerge软件,进行文件夹比较。把你自己做的项目文件夹,和我的可运行项目文件夹进行比较。 
这个软件很牛逼的,可以知道文件夹里哪两个文件不对,并且很明显地标记出来 
这里提供了绿色安装和使用教程:diffmerge 下载和使用教程
 步骤 4 : 

TestController

增加了日期对象,并且放在 "now" 这个变量上扔给视图
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.how2java.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.how2java.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,"product e"200);
        boolean testBoolean = true;
         
        Date now = new Date();
         
        List<Product> ps = new ArrayList<>();
        ps.add(new Product(1,"product a"50));
        ps.add(new Product(2,"product b"100));
        ps.add(new Product(3,"product c"150));
        ps.add(new Product(4,"product d"200));
        ps.add(currentProduct);
        ps.add(new Product(6,"product f"200));
        ps.add(new Product(7,"product g"200));       
         
        m.addAttribute("now", now);
        m.addAttribute("ps", ps);
        m.addAttribute("htmlContent", htmlContent);
        m.addAttribute("currentProduct", currentProduct);
        m.addAttribute("testBoolean", testBoolean);
         
        return "test";
    }
}
 步骤 5 : 

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>
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
<!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;
        }
        div.date p{
            padding-left:20px;
            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+999}" ></p>
</div>
 
<div class="showing">
    <div th:replace="include::footer1" ></div>
    <div th:replace="include::footer2(2015,2018)" ></div>
</div>
 
</body>
 
</html>
 步骤 6 : 

thymeleaf 内置工具

像 #date 这样的 thymeleaf内置工具有很多种,一共有如下16种。 
 
Execution Info
Messages
URIs/URLs
Conversions
Dates
Calendars
Numbers
Strings
Objects
Booleans
Arrays
Lists
Sets
Maps
Aggregates
IDs
 

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

Execution Info

1
2
3
4
5
6
7
${#execInfo.templateName}
${#execInfo.templateMode}
${#execInfo.processedTemplateName}
${#execInfo.processedTemplateMode}
${#execInfo.templateNames}
${#execInfo.templateModes}
${#execInfo.templateStack}
 步骤 8 : 

Messages

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
${#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)}
${#messages.setMsgOrNull(messageKeySet)}
 步骤 9 : 

URIs/URLs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
${#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)}
${#uris.unescapeQueryParam(uri, encoding)}
 步骤 10 : 

Conversions

1
2
${#conversions.convert(object, 'java.util.TimeZone')}
${#conversions.convert(object, targetClass)}
 步骤 11 : 

Dates

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
${#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()}
${#dates.createTodayForTimeZone()}
 步骤 12 : 

Calendars

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
${#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()}
${#calendars.createTodayForTimeZone()}
 步骤 13 : 

Numbers

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
${#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)}
${#numbers.sequence(from,to,step)}
 步骤 14 : 

Strings

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
${#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...)}
${#strings.randomAlphanumeric(count)}
 步骤 15 : 

Objects

1
2
3
4
${#objects.nullSafe(obj,default)}
${#objects.arrayNullSafe(objArray,default)}
${#objects.listNullSafe(objList,default)}
${#objects.setNullSafe(objSet,default)}
 步骤 16 : 

Booleans

1
2
3
4
5
6
7
8
9
10
11
12
13
14
${#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)}
${#bools.setOr(condSet)}
 步骤 17 : 

Arrays

1
2
3
4
5
6
7
8
9
10
11
${#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)}
${#arrays.containsAll(array, elements)}
 步骤 18 : 

Lists

1
2
3
4
5
6
7
8
${#lists.toList(object)}
${#lists.size(list)}
${#lists.isEmpty(list)}
${#lists.contains(list, element)}
${#lists.containsAll(list, elements)}
${#lists.sort(list)}
${#lists.sort(list, comparator)}
${#sets.toSet(object)}
 步骤 19 : 

Sets

1
2
3
4
${#sets.size(set)}
${#sets.isEmpty(set)}
${#sets.contains(set, element)}
${#sets.containsAll(set, elements)}
 步骤 20 : 

Maps

1
2
3
4
5
6
${#maps.size(map)}
${#maps.isEmpty(map)}
${#maps.containsKey(map, key)}
${#maps.containsAllKeys(map, keys)}
${#maps.containsValue(map, value)}
${#maps.containsAllValues(map, value)}
 步骤 21 : 

Aggregates

1
2
3
4
${#aggregates.sum(array)}
${#aggregates.sum(collection)}
${#aggregates.avg(array)}
${#aggregates.avg(collection)}
 步骤 22 : 

IDs

1
2
3
${#ids.seq('someId')}
${#ids.next('someId')}
${#ids.prev('someId')}

posted on 2019-01-04 17:16  我是司  阅读(809)  评论(0)    收藏  举报

导航