java—使用thymeleaf动态创建多个引导行以显示从数据库到我的web应用程序的所有产品的问题

nqwrtyyt  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(341)

我正在尝试用java、spring和thymeleaf做一个amazon克隆web应用程序。我的数据库中有多个产品,我想在页面中显示,如下所示(在本例中,我的数据库中有3个产品):

我使用thymeleaf th:each来遍历数据库中的产品。但是当我尝试放置多行时有一个问题。我使用引导行和列,以便每行有3个产品。当有3个以上的产品要显示时,我需要用thymeleaf动态添加另一行,问题就来了。以下是所有基本代码:
这是html:

  1. <div class="row" th:each="row : ${rows}">
  2. <div class="col-xl-4" th:each="product : ${products}">
  3. <div class="product-container">
  4. <div class="product">
  5. <p th:text="${product.getTitle()}"></p>
  6. <div class="d-flex justify-content-center">
  7. <small>$</small>
  8. <strong th:text="${product.getPrice()}"></strong>
  9. </div>
  10. <div class="d-flex justify-content-center mb-2">
  11. <i class="fas fa-star"></i>
  12. <i class="fas fa-star"></i>
  13. <i class="fas fa-star"></i>
  14. </div>
  15. <img th:src="${product.getImageUrl()}">
  16. <div class="d-flex justify-content-center">
  17. <button>Add To Cart</button>
  18. </div>
  19. </div>
  20. </div>
  21. </div>
  22. </div>

这是控制器:

  1. @Controller
  2. @RequiredArgsConstructor
  3. public class HomeController {
  4. private final ProductService productService;
  5. @GetMapping("/home")
  6. public ModelAndView showHome(){
  7. ModelAndView modelAndView = new ModelAndView();
  8. modelAndView.addObject("products", productService.getAllProducts());
  9. modelAndView.addObject("rows", productService.getRows());
  10. System.out.println(productService.getRows().size());
  11. return modelAndView;
  12. }
  13. }

这就是产品服务:

  1. @Service
  2. @RequiredArgsConstructor
  3. public class ProductService {
  4. private final ProductRepository productRepository;
  5. public List<ProductDto> getAllProducts(){
  6. List<ProductEntity> productsEntity = productRepository.findAll();
  7. List<ProductDto> productsDto = new ArrayList<>();
  8. for (ProductEntity product :
  9. productsEntity) {
  10. productsDto.add(ProductMapper.entityToDto(product));
  11. }
  12. return productsDto;
  13. }
  14. public List<Integer> getRows() {
  15. List<ProductEntity> productEntities = productRepository.findAll();
  16. List<Integer> rows = new ArrayList<>();
  17. int rowCount = productEntities.size() / 4;
  18. for (int i = 0; i <= rowCount; i++)
  19. rows.add(i);
  20. return rows;
  21. }
  22. }

如果我向数据库中再添加一个产品,则会发生这种情况,因此总共有4个产品:

当我有4个产品时,它应该添加另一行,并且第4个产品应该显示在该行上。我的整个逻辑是这样的:使用productservice中的getrows()计算应该添加多少行,考虑数据库中产品的数量,然后遍历产品。但我认为问题出在这里。对于每一行,我显示数据库中的每一个产品。我需要一种方法,只显示第一行的前3个产品,然后再显示第二行的下3个产品,等等。我如何实现这一点?

h22fl7wq

h22fl7wq1#

使用bootstrap,您不需要处理所有这些。要在每行中显示3个产品,您只需执行以下操作。

  1. <div class="row">
  2. <div class="col-xl-4" th:each="product : ${products}">
  3. <div class="product-container">
  4. </div>
  5. </div>
  6. </div>

col类表示每行可能使用的12列中的列数。所以,如果您想要三个等宽的列,可以使用.col-4。

相关问题