Thymeleaf 不显示我的迭代器的所有对象

问题描述 投票:0回答:1

我最近正在研究百里香,我的一个大学项目需要一些帮助。基本上,我必须应用迭代器模式设计来迭代对象列表,然后将它们打印在我网站上的视频上。我创建了自己的迭代器,但是当我尝试使用 thymeleaf 进行迭代时,仅打印列表的第一个元素,其他元素将被忽略。 我的迭代器的代码是:

public class ConcreteIterator<T> implements MyIterator<T> {
    private List<T> list;
    private int index;

    public ConcreteIterator(List<T> list) {
        this.list = list;
        this.index = 0;
    }

    @Override
    public boolean hasNext() {
        return index < list.size();
    }

    @Override
    public T next() {
        if (hasNext()) {
            T item = list.get(index);
            index++;
            return item;
        } else {
            throw new IndexOutOfBoundsException("No items left!");
        }
    }
}

Il codice thymeleaf è,invece,il seguente:

<div th:while="${gameIterator.hasNext()}">
      <div th:text="${gameIterator.getCurrent().getName()}"></div>
      <div th:text="${gameIterator.getCurrent().getDescription()}"></div>
      <th:block th:width="${gameIterator.next()}"></th:block>
</div>

我用这种方法解决了这个问题,现在打印整个列表:

<div th:each="i : ${#numbers.sequence(1, size)}">

    <div th:text="${gameIterator.getCurrent().getName()}"></div>
    <div th:text="${gameIterator.getCurrent().getDescription()}"></div>

    <div th:if="${gameIterator.hasNext()}">
        <th:block th:width="${gameIterator.next()}"></th:block>
    </div>

</div>

然而,这是一个非常强制的方法,如果可以的话,我希望只使用上面代码中的 while 来完成它(或者我也可以使用 javascript,但我不知道如何获取迭代器要迭代的 javascript 脚本)。感谢任何帮助我或给我提示的人!

javascript java html web thymeleaf
1个回答
0
投票

如果可能,请尝试将

th:each
Iterable
一起使用,而不是直接使用
Iterator

但是,如果这是不可能的,您可以使用

th:with

<div th:while="${gameIterator.hasNext()}">
    <th:block th:with="current=${gameIterator.next()}">
      <div th:text="${current.getName()}"></div>
      <div th:text="${current.getDescription()}"></div>
    </th:block>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.