1. Overview
1.概述
Thymeleaf is a Java template engine for processing and creating HTML.
Thymeleaf是一个用于处理和创建HTML的Java模板引擎。
In this quick tutorial, we’ll look into Thymeleaf’s lists utility object to perform common list-based operations.
在这个快速教程中,我们将了解Thymeleaf的lists工具对象,以执行基于列表的常见操作。
2. Computing Size
2.计算大小
First, the size method returns the length of a list. We can include it, say, via the th:text attribute:
首先,size方法返回一个列表的长度。我们可以通过th:text属性包含它。
size: <span th:text="${#lists.size(myList)}"/>
myList is our own object. We’d have passed it via the controller:
myList是我们自己的对象。我们会通过控制器来传递它。
@GetMapping("/size")
public String usingSize(Model model) {
model.addAttribute("myList", getColors());
return "lists/size";
}
3. Checking If the List Is Empty
3.检查列表是否为空
The isEmpty method returns true if the given list has no elements:
isEmpty方法如果给定的列表没有元素,则返回true。
<span th:text="${#lists.isEmpty(myList)}"/>
Generally, this utility method is used with conditionals – th:if and th:unless:
一般来说,这个实用方法是和条件式一起使用的–th:if和th:except。
<span th:unless="${#lists.isEmpty(myList)}">List is not empty</span>
4. Checking Membership
4.检查成员资格
The contains method checks whether an element is a member of the given list:
contains方法检查一个元素是否是给定列表中的成员。
myList contains red: <span th:text="${#lists.contains(myList, 'red')}"/>
Similarly, we can check the membership of multiple elements using the containsAll method:
同样,我们可以使用containsAll方法检查多个元素的成员资格。
myList contains red and green: <span th:text='${#lists.containsAll(myList, {"red", "green"})}'/>
5. Sorting
5.分拣
The sort method enables us to sort a list:
sort方法使我们能够对一个列表进行排序。
sort: <span th:text="${#lists.sort(myList)}"/>
sort with Comparator: <span th:text="${#lists.sort(myList, reverse)}"/>
Here we have two overloaded sort methods. Firstly, we’re sorting our list in the natural order – ${#lists.sort(myList)}. Secondly, we’re passing an additional parameter of type Comparator. In our example, we’re getting this comparator from the model.
这里我们有两个重载的sort方法。首先,我们以自然顺序对我们的列表进行排序–${#lists.sort(myList)}。其次,我们传递一个额外的Comparator类型的参数。在我们的例子中,我们从模型中获取这个比较器。
6. Converting to List
6.转换为List
Lastly, we can convert Iterables and arrays to Lists using the toList method.
最后,我们可以使用toList方法将Iterables和数组转换成Lists。
<span th:with="convertedList=${#lists.toList(myArray)}">
converted list size: <span th:text="${#lists.size(convertedList)}"/>
</span>
Here we’re creating a new List, convertedList, and then printing its size with #lists.size.
这里我们创建一个新的List,convertedList,然后用#lists.size.打印其大小。
7. Summary
7.摘要
In this tutorial, we’ve investigated the Thymeleaf built-in lists utility object and how to use it effectively.
在本教程中,我们研究了Thymeleaf内置的lists 实用对象以及如何有效使用它。
As always, the source code for all examples is available over on GitHub.
一如既往,所有实例的源代码都可以在GitHub上找到。