【问题标题】:Why <td th:each="i : ${#numbers.sequence(0, table_width)}" th:text="${rows[${i}]}"></td> not working为什么 <td th:each="i : ${#numbers.sequence(0, table_width)}" th:text="${rows[${i}]}"></td> 不起作用
【发布时间】:2019-07-04 21:37:15
【问题描述】:

我正在尝试遍历包含对象列表的列表,即 List 我想知道为什么这不起作用,只尝试了“i”,但没有运气。

List<Object[]> lists;  // logic
model.addObject("lists", lists);
model.addObject("table_width", lists.get(0).length);

Thymeleaf 代码片段

<table class="table table-responsive table-stripped table-collapsed table-bordered">
                <tr th:each="rows,rowStat : ${lists}">
                    <td th:text="${rowStat.count}"></td>

                    <td th:each="i : ${#numbers.sequence(0, table_width)}" th:text="${rows[${i}]}"></td>
                </tr>
</table>

【问题讨论】:

    标签: spring spring-boot thymeleaf


    【解决方案1】:

    我找到了办法,

    <td th:each="i : ${#numbers.sequence(0, table_width-1)}" th:text="${rows[__${i}__]}"></td>
    

    这就是诀窍

    【讨论】:

    • 在这种情况下,您不需要预处理。你应该使用th:text="${rows[i]}"
    【解决方案2】:

    您可以简单地对两个列表进行迭代。无需使用#numbers 助手。

    <table class="table table-responsive table-stripped table-collapsed table-bordered">
        <tr th:each="rows, rowStat : ${lists}">
            <td th:text="${rowStat.count}"></td>
            <td th:each="value: ${rows}" th:text="${value}"></td>
        </tr>
    </table>
    

    【讨论】:

      【解决方案3】:

      如果您正在迭代对象的集合(列表),请尝试以下示例:

      HTML:

      <div th:if="${not #lists.isEmpty(counts)}">
          <h2>Counts List</h2>
          <table class="table table-striped">
              <tr>
                  <th>Id</th>
                  <th>Name</th>
              </tr>
              <tr th:each="count : ${counts}">
                  <td th:text="${count.id}"></td>
                  <td th:text="${count.name}"></td>
              </tr>
          </table>
      </div>
      

      Java:

      public List<Count> listAll() {
          List<Count> counts = new ArrayList<>();
          countRepository.findAll().forEach(counts::add);
          return counts;
      }
      

      在 Thymeleaf 文档 - Iteration Basics 部分阅读更多信息。

      【讨论】:

      • 谢谢 Mebin,我是 Thymeleaf 的新手,我找到了解决方法。
      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 2016-10-16
      • 1970-01-01
      • 2017-06-19
      相关资源
      最近更新 更多