# Spring Boot & thymeleaf模板 使用 th:each 遍歷對象數組 -生成一批html標籤體

在controller中取出emps 對象數組

//1.查詢全部的員工,返回列表頁面
    @GetMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeDao.getAll();

        //放在model請求域中
        model.addAttribute("emps",employees);

        //thymeleaf 默認就會拼串 //public static final String DEFAULT_PREFIX = "classpath:/templates/xxx.html";
        //public static final String DEFAULT_SUFFIX = ".html";
        return "emp/list";
    }

在list.html中進行遍歷

<tbody>
								<tr th:each="emp:${emps}">
									<td th:text="${emp.id}"></td>
									<td th:text="${emp.lastName}"></td>
									<td th:text="${emp.email}"></td>
									<td th:text="${emp.gender}==1?'男':'女'"></td>
									<td th:text="${emp.department.departmentName}"></td>
									<td th:text="${#dates.format(emp.birth, 'yyyy-MM-dd')}"></td>
									<td>
										<button class="btn btn-sm btn-primary">編輯</button>
										<button class="btn btn-sm btn-danger">刪除</button>
									</td>
								</tr>
							</tbody>

結果展現

相關文章
相關標籤/搜索