胸腺循环并每n个项目分组

时间:2018-09-19 09:02:42

标签: java spring 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>

1 个答案:

答案 0 :(得分:0)

为什么不将分组逻辑移到视图层之外? Thymeleaf对数据计算不太友好。 而不是简单的列表列表:

List<String> myList;

将替换为:

List<List<String>> myList;

您的百里香代码将如下所示:

    <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>