gpt4 book ai didi

java - Thymeleaf 循环并按每 n 个项目分组

转载 作者:行者123 更新时间:2023-11-30 10:11:30 25 4
gpt4 key购买 nike

我正在使用 thymeleaf,我想迭代一个循环并按每 n 个项目进行分组。现在我的代码想要每 4 个项目进行分组。在搜索了大部分问题之后,这是我的代码:

<div th:each="items, iter: ${myList}" th:if="${iter.count} % 4 == 0" th:class="${iter.first}? 'nice-slider-slide active first' : 'nice-slider-slide'">
<div class="nice-slider-entry" th:each="item, iter: ${items}">
<span th:text="${item.getName}"></span>
</div>
</div>

结果是空白的,没有打印任何东西。但是我想要的结果是:

<div class="nice-slider-slide active first">
<div class="nice-slider-entry">
<span>Name</span>
</div>
<div class="nice-slider-entry">
<span>Name</span>
</div>
<div class="nice-slider-entry">
<span>Name</span>
</div>
<div class="nice-slider-entry">
<span>Name</span>
</div>
</div>
<div class="nice-slider-slide">
<div class="nice-slider-entry">
<span>Name</span>
</div>
<div class="nice-slider-entry">
<span>Name</span>
</div>
<div class="nice-slider-entry">
<span>Name</span>
</div>
<div class="nice-slider-entry">
<span>Name</span>
</div>
</div>

最佳答案

为什么不把分组的逻辑移到 View 层外面呢? Thymeleaf 对数据计算不太友好。而不是一个简单的列表有一个列表的列表:

List<String> myList;

替换为:

List<List<String>> myList;

你的 thymeleaf 代码将是这样的:

    <div th:each="subList,iter : ${myList}" th:class="${iter.first}? 'nice-slider-slide active first' : 'nice-slider-slide'">
<div class="nice-slider-entry" th:each="index: ${subList}">
<span th:text="${index}"></span>
</div>
</div>

更新纯 Thymeleaf 解决方案:

<th:block th:with="noEl = 4,totalSize = ${#lists.size(myList)} - 1">
<th:block th:each=" listIndex: ${#numbers.sequence(0, totalSize, noEl)}">
<div th:class="${listIndex eq 0 }? 'nice-slider-slide active first' : 'nice-slider-slide'"
th:with="maxValue = ${ totalSize lt (listIndex + noEl -1) ? totalSize : listIndex + noEl -1}">
<div class="nice-slider-entry" th:each="index : ${#numbers.sequence(listIndex, maxValue)}">
<span th:text="${myList[index]}"></span>
</div>
</div>
</th:block>
</th:block>

关于java - Thymeleaf 循环并按每 n 个项目分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52402041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com