
3.11 Thymeleaf数据处理
在Thymeleaf模板中还支持集合方法调用、字符串方法调用、日期格式化等操作。例如,在使用List集合的时候可以考虑采用get()方法获取指定索引的数据,那么在使用Set集合的时候会考虑使用contains()来判断某个数据是否存在,使用Map集合的时候也可以使用containsKey()判断某个key是否存在,以及使用get()根据key获取对应的value。
1.【mldnboot-thymeleaf项目】修改src/main/view/templates/message/message_map.html页面,调用Map方法。

2.【mldnboot-thymeleaf项目】如果传递的是Set集合,也可以利用Set接口中的contains()方法判断某个值是否存在。
在ThymeleafController控制器中追加一个新的方法,利用Set传递属性。

建立src/main/view/templates/message/message_set.html页面,判断某一个内容是否在集合中存在。
<p th:if="${#sets.contains(allInfos,'mldn')}">存在有“mldn”的信息!</p>
此时会判断在allInfos集合中是否存在mldn的内容,同时也可以利用size()方法获取集合长度,页面运行效果如图3-16所示。

图3-16 判断Set集合是否有指定数据
3.【mldnboot-thymeleaf项目】在进行数据处理的时候,也可以直接使用字符串String类中定义的方法。
在ThymeleafController控制器中追加一个新的方法,用于传递字符串属性。

建立src/main/view/templates/message/message_string.html页面,以处理字符串。

在进行字符串数据处理时,可以直接使用控制器传递过来的属性,也可以直接定义具体的字符串内容。本程序处理后的结果如图3-17所示。

图3-17 字符串处理
4.【mldnboot-thymeleaf项目】在Thyemeleaf中还可以对输出的日期类型进行格式化处理。
在ThymeleafController控制器中追加一个新的方法,用于传递Date属性。

建立src/main/view/templates/message/message_date.html页面,以格式化日期显示。

本程序使用两种方式实现了日期时间的格式化处理,页面运行效果如图3-18所示。

图3-18 格式化日期时间