【问题标题】:Limit number of displayed items with th:each使用 th:each 限制显示项目的数量
【发布时间】:2014-12-26 20:11:03
【问题描述】:

在以下 thymeleaf 代码中,我想将列表 produtos 中显示的项目数限制为特定数字:

  <div class="col-xs-6 col-lg-4" th:each="item2 : ${produtos}" th:if="${item.getId() == item2.getCategoria().getId()}">
    <h2 th:text="${item2.getNome()}"></h2>
    <div class="row">
      <div class="col-xs-6 col-md-3">
        <a th:href="@{/produto/__${item2.getId()}__.htm}" class="thumbnail">
          <img th:src="@{/Produto/icone__${item2.getId()}__.jpeg}" width="64" height="64" th:alt="${item2.getNome()}"/>
        </a>
      </div>
    </div>
    <p th:text="${#strings.substring(item2.getDescricao(), 0, 140)}"></p>
    <p><a class="btn btn-default" th:href="@{/produto/__${item2.getId()}__.htm}" role="button">Detalhes &raquo;</a></p>
  </div>

但在官方文档中我找不到任何说明如何执行此操作的内容。任何人都可以提供任何提示吗?

更新

我尝试将这个添加到我的代码中来解决这个问题:

th:if="${itemStat.index < NUM}"

最后的代码是这样的:

<div class="col-xs-6 col-lg-4" th:each="item2 : ${produtos}" th:if="${item2Stat.index < NUM}" th:if="${item.getId() == item2.getCategoria().getId()}">

但我收到此错误:

org.xml.sax.SAXParseException: the value of the attribute "th:if" associated to an element "null" shouldn't have the character '<'.

【问题讨论】:

    标签: java spring spring-boot thymeleaf


    【解决方案1】:

    你可以在你的 th:each 属性中使用第二个参数,就像你的例子一样:

    <div class="col-xs-6 col-lg-4" th:each="item2, stat : ${produtos}" th:if="${item.getId() == item2.getCategoria().getId()}">
    

    那么您可以访问此属性中的其他数据。完整的解释在这里: http://www.thymeleaf.org/doc/usingthymeleaf.html#iteration 在主题 6.2 下

    【讨论】:

    • 这对我不起作用,因为循环 item2 : ${produtos} 被放置在另一个;每个循环遍历恒定数量的元素并在列表中的不同位置选择其中一些元素。适合这里的解决方案是每次迭代增加一个变量,当这个变量达到特定数字时。打破循环。
    【解决方案2】:

    我设法解决了这个问题,将此添加到我的代码中:

    th:each="item2 : ${#numbers.sequence(1,3)}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多