Thymeleaf学习(三)

thymeleaf流程控制

Posted by 独顽且鄙 on May 3, 2016

迭代循环

th:each

我们在模板中最常用的循环就是表格了,在示例程序中就有这样一个例子—/WEB-INF/templates/product/list.html ,在这个页面中,我们将查询出的所有产品放到list中,并将list存入上下文中。

public void process(
        HttpServletRequest request, HttpServletResponse response,
        ServletContext servletContext, TemplateEngine templateEngine) {

    ProductService productService = new ProductService();
    List<Product> allProducts = productService.findAll(); 

    WebContext ctx = new WebContext(request, servletContext, request.getLocale());
    ctx.setVariable("prods", allProducts);

    templateEngine.process("product/list", ctx, response.getWriter());
}

在模板中,我们用th:each来进行循环

<table>
    <tr>
       <th>NAME</th>
       <th>PRICE</th>
       <th>IN STOCK</th>
    </tr>
    <tr th:each="prod : ${prods}">
       <td th:text="${prod.name}">Onions</td>
       <td th:text="${prod.price}">2.41</td>
       <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    </tr>
</table>

我们不仅可以通过th:each 来迭代List,还可以用来迭代很多对象,例如:

  • 所有实现了java.util.Iterable接口的对象
  • 所有实现了java.util.Map的对象
  • 数组
  • 所有对象–因为都可以看做只包含自身的列表

迭代状态

Thymeleaf提供了一组迭代状态,方便在循环时使用

  • index ,当前索引,从0开始
  • count ,当前索引,从0开始
  • size ,被迭代对象的总数,例如List的size
  • current ,The iter variable for each iteration(官方原文,没太明白)
  • even/odd ,boolean值,当前的迭代是否是奇数或偶数
  • first/last ,boolean值,当前的迭代是否是第一个或最后一个

我们通常都有这样的需求,表格为了美观,会隔行变色。 这时我们就可以使用迭代变量的even/odd 状态,使用方法如下:

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
  </tr>
  <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  </tr>
</table>

在上面的代码中,iterStat是我们创建的迭代状态变量。如果没有创建,Thymeleaf会自动创建一个状态变量,名字就是迭代变量的名字加上Stat后缀:

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
  </tr>
  <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  </tr>
</table>

条件表达式

if unless

例:

<a href="comments.html"
   th:href="@{/product/comments(prodId=${prod.id})}" 
   th:if="${not #lists.isEmpty(prod.comments)}">view</a>

代码运行的结果就是,如果prod.comments不是空的,就输出<a>标签,如下图:

switch

例:

<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>

其中th:case=”*“就是switch中的default