【问题标题】:Thymeleaf counter variable not incrementingThymeleaf 计数器变量不递增
【发布时间】:2019-04-05 17:19:31
【问题描述】:

在使用 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>

【问题讨论】:

    标签: spring spring-boot thymeleaf counter increment


    【解决方案1】:

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

    在服务器端实现一个名为 Counter 的简单类:

    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>
    

    【讨论】:

    • 您的课程中没有 incrementAndGet - 但是...开发人员必须做点什么,对吗? ;)
    • @jonasheinisch 你是对的,谢谢你提到它。我修好了。
    【解决方案2】:

    这是由于范围可变,它是在Thymeleaf issue 666 中使用替代方法提出的:

    由于变量的作用域是元素,您可能无法使用 th:with 获得总值,因此您需要查看其他地方。

    另一种解决方案是在控制器中处理结果,将结果存储到模型属性,然后在视图中使用该结果。例如,在 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>
    

    【讨论】:

    • 好的,我可以在我的model 上设置一个int 并使用百里香th:with 增加int 变量
    • @Samim 您可以在链接中进一步阅读更复杂的解决方案和全面的解释
    • 感谢您的宝贵时间。到现在还没有解决办法,只能这么说。
    猜你喜欢
    • 1970-01-01
    • 2023-02-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2017-06-27
    • 2019-09-13
    • 2021-07-21
    • 1970-01-01
    相关资源
    最近更新 更多