thymeleaf 获得前 3 个对象

Rom*_*hok 1 java spring spring-mvc thymeleaf spring-boot

请你帮助我好吗。我想展示产品中的前 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>
Run Code Online (Sandbox Code Playgroud)

控制器:

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

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

谢谢。

wan*_*arn 5

由于products是 list of Product,因此您必须迭代该列表。在 thymeleaf 上,您可以使用th:each属性来进行迭代。因此,对于您的情况,您可以使用如下所示的内容。试一试。

<th:each="product,iterStat: ${products}" th:if="${iterStat.index} <3">
Run Code Online (Sandbox Code Playgroud)

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