# 6.2 保持遍历状态

当使用`th:each`时，Thymeleaf提供了一种有用的机制来跟踪遍历的状态：状态变量。

状态变量定义在`th:each`属性里，并包含以下数据：

* 当前的遍历索引，从0开始。此为index属性。
* 当前的遍历索引，从1开始。此为count属性。
* 被遍历变量里的元素数量。此为size属性。
* 每次遍历的遍历变量。此为current属性。
* 当前的遍历是偶数次还是奇数次。此为even/odd布尔属性。
* 当前是否为首次遍历。此为first布尔属性。
* 当前是否为最后一次遍历。此为last布尔属性。

让我们看看怎么在之前的例子里使用它：

```markup
<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
  </tr>
  <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  </tr>
</table>
```

状态变量（此例子里的`iterStat`）定义在`th:each`属性里，跟在遍历变量后面，由逗号分隔。就像遍历变量一样，状态变量的作用范围也是在由持有`th:each`属性的标签定义的代码片段之上。

让我们看一下处理我们的模版的结果：

```markup
<!DOCTYPE html>

<html>

  <head>
    <title>Good Thymes Virtual Grocery</title>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
    <link rel="stylesheet" type="text/css" media="all" href="/gtvg/css/gtvg.css" />
  </head>

  <body>

    <h1>Product list</h1>

    <table>
      <tr>
        <th>NAME</th>
        <th>PRICE</th>
        <th>IN STOCK</th>
      </tr>
      <tr class="odd">
        <td>Fresh Sweet Basil</td>
        <td>4.99</td>
        <td>yes</td>
      </tr>
      <tr>
        <td>Italian Tomato</td>
        <td>1.25</td>
        <td>no</td>
      </tr>
      <tr class="odd">
        <td>Yellow Bell Pepper</td>
        <td>2.50</td>
        <td>yes</td>
      </tr>
      <tr>
        <td>Old Cheddar</td>
        <td>18.75</td>
        <td>yes</td>
      </tr>
    </table>

    <p>
      <a href="/gtvg/" shape="rect">Return to home</a>
    </p>

  </body>

</html>
```

注意：我们的遍历状态变量完美地工作了，只在奇数行上建立了`odd`CSS类。

如果你不明确地设置一个状态变量，Thymeleaf总是会通过在遍历变量的名字后加上后缀`Stat`为你创建一个状态变量：

```markup
<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
  </tr>
  <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  </tr>
</table>
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jack80342.gitbook.io/thymeleaf/i.-using-thymeleaf/6-iteration/6.2-keeping-iteration-status.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
