Thymeleaf 计数器变量不递增

Thymeleaf counter variable not incrementing

我想在使用 thymeleaf 渲染我的 html 时拥有一个整数类型的计数器变量,但计数器变量意外增加。下面是我的代码。请帮忙。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en"
      xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div th:with="mycounter = 0">
    <div th:with="mycounter=${mycounter + 1}">
        <span th:text="${mycounter}"></span> <!-- result: 1 -->
    </div>
    <div th:with="mycounter=${mycounter + 1}">
        <span th:text="${mycounter}"></span> <!-- result: 1 , expected: 2-->
    </div>
</div>
</body>
</html>

这是由于变量作用域,它是在 Thymeleaf issue 666 中使用替代方法提出的:

Since making variables are scoped to the element, you might not be able to get a total value using th:with, so you'll need to look elsewhere.

One alternative solution would be to process the result in your controller, store the result to a model attribute, then use that result in the view. For example, in Spring:

public String yourControllerEndpoint(Model model) {
 int total = // get the total of your list
 model.addAttribute("total", total);
 return "your-template";
}
<table>
 <!-- Your looping display code here -->
  ...
  <span th:text="${total}">Total will go here</span>
</table>

您可以使用以下方法实现它:

在 server-side 上实现一个简单的 class 调用计数器:

public class Counter
{
    private int count;

    public Counter()
    {
        count = 0;
    }

    public Counter(int init)
    {
        count = init;
    }

    public int get()
    {
        return count;
    }

    public void clear()
    {
        count = 0;
    }

    public int incrementAndGet()
    {
        return ++count;
    }

    public String toString()
    {
        return ""+count;
    }
}

在您的 servlet 代码中添加:

context.addAttribute("counter", new Counter());

在您的模板中,您可以像这样使用和增加它:

<div th:with="mycounter = ${counter.get()}">
    <div th:with="mycounter=${counter.incrementAndGet()}">
        <span th:text="${mycounter}"></span> <!-- result: 1 -->
    </div>
    <div th:with="mycounter=${counter.incrementAndGet()}">
        <span th:text="${mycounter}"></span> <!-- result: 2 , expected: 2-->
    </div>
</div>