使用th:each

对于我们的产品列表页面,我们需要一个控制器方法,来从服务层获得产品列表,并把它添加到模版上下文:

  1. public void process(
  2. final HttpServletRequest request, final HttpServletResponse response,
  3. final ServletContext servletContext, final ITemplateEngine templateEngine)
  4. throws Exception {
  5. ProductService productService = new ProductService();
  6. List<Product> allProducts = productService.findAll();
  7. WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());
  8. ctx.setVariable("prods", allProducts);
  9. templateEngine.process("product/list", ctx, response.getWriter());
  10. }

然后,我们在我们的模版里使用th:each来遍历产品列表:

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <title>Good Thymes Virtual Grocery</title>
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  6. <link rel="stylesheet" type="text/css" media="all"
  7. href="../../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
  8. </head>
  9. <body>
  10. <h1>Product list</h1>
  11. <table>
  12. <tr>
  13. <th>NAME</th>
  14. <th>PRICE</th>
  15. <th>IN STOCK</th>
  16. </tr>
  17. <tr th:each="prod : ${prods}">
  18. <td th:text="${prod.name}">Onions</td>
  19. <td th:text="${prod.price}">2.41</td>
  20. <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  21. </tr>
  22. </table>
  23. <p>
  24. <a href="../home.html" th:href="@{/}">Return to home</a>
  25. </p>
  26. </body>
  27. </html>

你在上面看到的那个prod : ${prods}属性值的意思是“对于求值${prods}结果里的每一个元素,重复这段模版,在一个叫作prod的变量里使用当前的元素”。让我们给看到的每一个东西取一个名字:

  • 我们把${prods}称为被遍历表达式或者被遍历变量。
  • 我们把prod称为遍历变量。

需要注意prod遍历变量的作用范围是<tr>元素,这意味着可以使用内部标签,像<td>