【问题标题】:thymeleaf get first 3 objectsthymeleaf 获得前 3 个对象
【发布时间】:2018-11-28 18:45:44
【问题描述】:

你能帮帮我吗? 我想从产品中展示我的前 3 个对象,但我不知道它必须是怎样的。 我尝试使用百里香序列,但它不起作用。也许有人可以提示我如何做到这一点。

HTML:

<th:block th:each="product:${products}">

<a  th:class="production_Page" th:href="@{'product/'+${product.id}}"> <p 
th:text="${product.productName}"/></a>

<a th:class="production_Page" 
th:href="@{'productDelete/'+${product.id}}">Delete</a>

<a th:class="production_Page" 
th:href="@{'productEdit/'+${product.id}}">Edit</a>

<img  th:class="productImage" th:src="${product.pathImage}"/>
<br/>
</th:block>

控制器:

@GetMapping("/products")
public String seeAllProductsIntoAList(Model model){
    model.addAttribute("products", productService.findAll());
    model.addAttribute("categories", categoryService.findAll());
    return "/productView/products";
}

如果有人能提示我这个问题,那就太好了。

谢谢。

【问题讨论】:

  • productService.findAll() 会返回什么?
  • @Override public List findAll() { return dao.findAll(); }

标签: java spring spring-mvc spring-boot thymeleaf


【解决方案1】:

由于productsProduct 的列表,您必须遍历该列表。在 thymeleaf 上,您可以使用 th:each 属性进行迭代。因此,对于您的情况,您可以使用以下内容。试试看吧。

<th:each="product,iterStat: ${products}" th:if="${iterStat.index} <3">

我不完全确定,但根据您的问题,您只需要前三个对象。为此,您可以使用th:each 中定义的状态变量。更多详情,您可以找到here

【讨论】:

    【解决方案2】:

    这是使用 #{numbers} 上下文对象的方法。

    <th:block th:each="i: ${#numbers.sequence(0, 2)}" th:with="product=${products[i]}">
        <a th:class="production_Page" th:href="@{'product/'+${product.id}}">
            <p th:text="${product.productName}"/>
        </a>
    
        <a th:class="production_Page" th:href="@{'productDelete/'+${product.id}}">Delete</a>
        <a th:class="production_Page" th:href="@{'productEdit/'+${product.id}}">Edit</a>
        <img  th:class="productImage" th:src="${product.pathImage}"/>
    
        <br/>
    </th:block>
    

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 1970-01-01
      • 2011-03-23
      • 2022-11-30
      • 2018-04-25
      • 2017-02-22
      • 2021-07-27
      • 2017-08-26
      • 2020-12-20
      相关资源
      最近更新 更多