Thymeleaf迭代列表

本文章將介紹Thymeleaf標準表達式語法中的概念。我們將使用th:each標記在模板中迭代產品列表。

編輯源代碼以便將產品列表顯示爲表格行。已經將Product類的對象列表設置爲具有變量名稱productList的上下文模型(參考:MyController.java中的實現)。

如果要上機實踐,請參考:Thymeleaf+SpringMVC5示例項目。這裏不再重複創建項目的過程,這裏將只介紹如何使用Thymeleaf標準表達式和標籤。

這裏創建一個Maven Web項目: thymeleaf-tutorials ,其目錄結構如下所示 -
Thymeleaf迭代列表

數據訪問類的實現:DAO.java -


package com.yiibai.dao;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.yiibai.spring.bean.*;

/**
 * Mock persistence.
 */
public class DAO {

    private static final String NO_WEBSITE = null;

    public static Product loadProduct() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return new Product("Wooden wardrobe with glass doors", Integer.valueOf(850), sdf.parse("2013-02-18"));
        } catch (ParseException ex) {
            throw new RuntimeException("Invalid date");
        }
    }

    public static List<Product> loadAllProducts() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Product> products = new ArrayList<Product>();
        try {
            products.add(new Product("花生油", Integer.valueOf(125), sdf.parse("2018-02-18")));
            products.add(new Product("蘇打餅乾", Integer.valueOf(15), sdf.parse("208-02-15")));
            products.add(new Product("拿鐵", Integer.valueOf(45), sdf.parse("2019-02-20")));
            products.add(new Product("調和油", Integer.valueOf(20), sdf.parse("2019-02-21")));
            products.add(new Product("大豆油", Integer.valueOf(49), sdf.parse("2019-02-15")));
            products.add(new Product("玉米汁", Integer.valueOf(80), sdf.parse("2019-02-17")));
        } catch (ParseException ex) {
            throw new RuntimeException("Invalid date");
        }
        return products;
    }



    public static Timestamp loadReleaseDate() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date date = sdf.parse("2014-01-31 15:00");
            return new Timestamp(date.getTime());
        } catch (ParseException ex) {
            throw new RuntimeException("Invalid date");
        }
    }

}

控制器類的實現:MyController.java -

package com.yiibai.spring.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.yiibai.dao.DAO;
import com.yiibai.spring.bean.Product;

@Controller
public class MyController {

    @GetMapping("/")
    public String index(Model model) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Product product = new Product("花生油", 129, sdf.parse("2018-02-18"));
        model.addAttribute("product", product);
        return "index";
    }

    @GetMapping("/escape")
    public String escape(Model model) throws ParseException {
        String html = "Welcome to our <b>fantastic</b> grocery store!";
        model.addAttribute("html", html);
        return "escape";
    }

    @GetMapping("/iteration")
    public String iteration(Model model) throws ParseException {
        List productList = DAO.loadAllProducts();
        model.addAttribute("productList", productList);
        return "iteration";
    }
}

模板文件的實現:/webapp/WEB-INFO/views/iteration.html -

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" th:href="@{/css/main.css}" />
<title>SpringMVC5+Thymeleaf迭代器示例</title>
</head>
<body>
    <h2>Spring MVC5 + Thymeleaf迭代器示例</h2>
    <table>
        <thead>
            <tr>
                <th>產品名稱</th>
                <th>價格</th>
                <th>有效日期</th>
            </tr>
        </thead>
        <tbody th:remove="all-but-first">
            <tr th:each="product : ${productList}">
                <td th:text="${product.description}">Red chair</td>
                <td th:text="${'¥' + #numbers.formatDecimal(product.price, 1, 2)}">¥350</td>
                <td th:text="${#dates.format(product.availableFrom, 'dd-MM-yyyy')}">2018-02-20</td>
            </tr>
            <tr>
                <td>White table</td>
                <td>¥200</td>
                <td>2018-04-10</td>
            </tr>
            <tr>
                <td>Reb table</td>
                <td>¥200</td>
                <td>2018-02-20</td>
            </tr>
            <tr>
                <td>Blue table</td>
                <td>¥200</td>
                <td>2018-02-20</td>
            </tr>
        </tbody>
    </table>

</body>
</html>

運行上面項目,在瀏覽器中顯示效果如下 -
Thymeleaf迭代列表

如何爲每一行添加序號?

重新編寫模板代碼,模板文件的實現:/webapp/WEB-INFO/views/iteration.html -

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" th:href="@{/css/main.css}" />
<title>SpringMVC5+Thymeleaf迭代器示例</title>
</head>
<body>
    <h2>Spring MVC5 + Thymeleaf迭代器示例</h2>
    <table>
        <thead>
            <tr>
            <th>行序號</th>
                <th>產品名稱</th>
                <th>價格</th>
                <th>有效日期</th>
            </tr>
        </thead>
        <tbody th:remove="all-but-first">
            <tr th:each="product : ${productList}">
            <td th:text="${productStat.count}">1</td>
                <td th:text="${product.description}">Red chair</td>
                <td th:text="${'¥' + #numbers.formatDecimal(product.price, 1, 2)}">¥350</td>
                <td th:text="${#dates.format(product.availableFrom, 'dd-MM-yyyy')}">2018-02-20</td>
            </tr>
            <tr>
                <td>White table</td>
                <td>¥200</td>
                <td>2018-04-10</td>
            </tr>
            <tr>
                <td>Reb table</td>
                <td>¥200</td>
                <td>2018-02-20</td>
            </tr>
            <tr>
                <td>Blue table</td>
                <td>¥200</td>
                <td>2018-02-20</td>
            </tr>
        </tbody>
    </table>

</body>
</html>

運行得到結果如下 -
Thymeleaf迭代列表

0 條評論,你可以發表評論,我們會進行改進
Comment author placeholder