问题
Could you please help me. I want to display my first 3 objects from product, I don't how it must be. I try to use thymeleaf sequence, but it don't work. Maybe somebody can hint me how it could be done.
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>
Controller:
@GetMapping("/products")
public String seeAllProductsIntoAList(Model model){
model.addAttribute("products", productService.findAll());
model.addAttribute("categories", categoryService.findAll());
return "/productView/products";
}
It would be great if somebody can hint me with this issue.
Thank you.
回答1:
Since products is list of Product, you have to iterate over that list. On thymeleaf you can use th:each attribute to do iteration. So for your case you can use something as below. Give it a try.
<th:each="product,iterStat: ${products}" th:if="${iterStat.index} <3">
I am not entirely sure but based on your question you wanted only first three objects. For this you can use status variable that are defined in th:each. More detail you can find here.
回答2:
Here's the way you do it with the #{numbers} context object.
<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>
来源:https://stackoverflow.com/questions/53526117/thymeleaf-get-first-3-objects