Iteration in Thymeleaf – Thymeleaf中的迭代

最后修改: 2018年 4月 28日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Thymeleaf is a versatile Java template engine for processing XML, XHTML and HTML5 documents.

Thymeleaf一个多功能的Java模板引擎,用于处理XML、XHTML和HTML5文档

In this quick tutorial, we’ll take a look at how we can perform iteration with Thymeleaf, along with some other features provided by the library.

在这个快速教程中,我们将看看如何用Thymeleaf进行迭代,以及该库所提供的一些其他功能。

For more information about Thymeleaf, take a look at our introductory article here.

关于Thymeleaf的更多信息,请看我们的介绍性文章这里

2. Maven Dependencies

2.Maven的依赖性

To create this example, we’ll be using Spring Framework libraries together with Thymeleaf libraries.

为了创建这个例子,我们将使用Spring框架库和Thymeleaf库。

Here we can see our dependencies (thymeleaf and thymeleaf-spring):

这里我们可以看到我们的依赖关系(thymeleafthymeleaf-spring)。

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.0.11.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.11.RELEASE</version>
</dependency>

3. Example Set-up

3.设置实例

Before we jump into the view layer, let’s create the MVC structure for our example.

在我们进入视图层之前,让我们为我们的例子创建MVC结构。

Starting with the snippet code of the model layer:

从模型层的代码片断开始。

public class Student implements Serializable {
    private Integer id;
    private String name;
    // standard contructors, getters, and setters
}

Let’s also provide the controller method responsible for loading the model and returning it to the view layer:

让我们也提供控制器方法,负责加载模型并将其返回到视图层。

@GetMapping("/listStudents")
public String listStudent(Model model) {
    model.addAttribute("students", StudentUtils.buildStudents());
    return "listStudents.html";
}

In our sample above the buildStudents() method simply returns a list of Student objects which we then add to the model.

在我们上面的例子中,buildStudents()方法只是返回一个Student对象的列表,然后我们将其添加到model

4. The th:each Attribute

4.th:each属性

In Thymeleaf, iteration is achieved by using the th:each attribute.

在Thymeleaf中,迭代是通过使用th:each属性实现的。

One of the interesting things about this attribute is that it will accept and iterate over some different data types, such as:

这个属性的一个有趣之处在于,它将接受并迭代一些不同的数据类型如:。

  • objects implementing java.util.Iterable 
  • objects implementing java.util.Map
  • arrays
  • any other object is treated as if it were a single-valued list containing one element

Now let’s invoke the th:each attribute with the data we set up in our example above:

现在让我们用我们在上面的例子中设置的数据来调用th:each属性

<tr th:each="student: ${students}">
    <td th:text="${student.id}" />
    <td th:text="${student.name}" />
</tr>

The code snippet shows the th:each iterating over our list of Students. The model attribute is accessed using the ${} notation, and each element of the list is passed to the body of the loop via the student variable.

这段代码显示了th:each在我们的Students列表中的迭代。模型属性使用${}访问。注解,列表中的每个元素都通过student变量传递给循环的主体。

5. Status Variable

5.状态变量

Thymeleaf also enables a useful mechanism to keep track of the iteration process via the status variable.

Thymeleaf还启用了一个有用的机制,通过status变量跟踪迭代过程

The status variable provides the following properties:

状态变量提供以下属性。

  • index: the current iteration index, starting with 0 (zero)
  • count: the number of elements processed so far
  • size: the total number of elements in the list
  • even/odd: checks if the current iteration index is even or odd
  • first:  checks if the current iteration is the first one
  • last: checks if the current iteration is the last one

Let’s see how the status variable works in our example:

让我们看看状态变量在我们的例子中是如何工作的。

<tr 
  th:each="student, iStat : ${students}" 
  th:style="${iStat.odd}? 'font-weight: bold;'" 
  th:alt-title="${iStat.even}? 'even' : 'odd'">
    <td th:text="${student.id}" />
    <td th:text="${student.name}" />
</tr>

Here, we included the iStat.odd property to evaluate the condition and set a bold style for the current row. The same is done on the next evaluation, but this time we are using iStat.even to print a value via alt/title HTML attribute.

在这里,我们包含了iStat.odd属性来评估条件并为当前行设置一个粗体样式。在下一次评估中也是如此,但这次我们使用iStat.even通过alt/title HTML属性打印一个值。

In case we omit the explicit creation of status variable (presented as iStat in our example), we could invoke our status variable by simply using the studentStatwhich is the aggregation of the variable student with the suffix Stat.

如果我们省略了状态变量(在我们的例子中以iStat呈现)的明确创建,我们可以通过简单地使用studentStat来调用我们的状态变量,它是变量student的聚合,后缀为Stat.

6. Conclusion

6.结论

In this article, we’ve explored one of the many features provided by the Thymeleaf library.

在这篇文章中,我们探讨了Thymeleaf库所提供的众多功能之一。

We presented iteration in Thymeleaf by using the attribute th:each, along with its out-of-the-box properties.

我们通过使用属性th:each,以及其开箱即用的属性,在Thymeleaf中展示了迭代。

A working version of the code shown in this article is available in our GitHub repository.

本文所示代码的工作版本可在我们的GitHub 仓库中找到。