案例:
**
- Thymeleaf遍历的语法格式:
**
emp为单个数据名称,${emps}为后台传送的变量名,使用th:each=""
进行数据遍历
<tr th:each="emp:${emps}">
th:text=""
进行取值,idea在调用方法时会进行提示
<td th:text="${emp.getId()}"></td>
或者使用:[[${}]]
行内写法,也可以进行取值
<td>[[${emp.getLastName()}]]</td>
${==?:}
三元运算符取值:
${emp.getGender()==0?'女':'男'}
${#dates.format(值, 'dd/MMM/yyyy HH:mm')}
日期格式调整:
${#dates.format(emp.getBirth(), 'dd/MMM/yyyy HH:mm')}
跳转传值th:href="@{/路径/}+${值}
":注意{/路径/}
th:href="@{/toUpdateEmp/}+${emp.getId()}"
总代码:
<table class="table table-striped table-sm">
<thead>
<tr>
<th>id</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th>department</th>
<th>birth</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="emp:${emps}">
<td th:text="${emp.getId()}"></td>
<td>[[${emp.getLastName()}]]</td>
<td th:text="${emp.getEmail()}"></td>
<td th:text="${emp.getGender()==0?'女':'男'}"></td>
<td th:text="${emp.getDepartment().getDepartmentName()}"></td>
<td th:text="${#dates.format(emp.getBirth(), 'dd/MMM/yyyy HH:mm')}"></td>
<td>
<a class="btn btn-sm btn-primary" th:href="@{/toUpdateEmp/}+${emp.getId()}">编辑</a>
<a class="btn btn-sm btn-danger" th:href="@{/delemp/}+${emp.getId()}">删除</a>
</td>
</tr>
</tbody>
</table>
**
- 表单传值案例:
**
表单赋值:th:value="${}
th:value="${employee.getId()}
单选框赋值:th:checked="${表达式}"
th:checked="${employee.getGender()==1}"
多选框赋值:th:selected="${表达式}"
th:selected="${department.getId()==employee.getDepartment().getId()}"
表单日期格式转换:th:value="${值,'yyyy-MM-dd HH:mm')}"
th:value="${#dates.format(employee.getBirth(),'yyyy-MM-dd HH:mm')}"
总代码:
<form th:action="@{/updateEmp}" method="post">
<input type="hidden" class="form-control" name="id" th:value="${employee.getId()}">
<div class="form-group">
<lable>LastName</lable>
<input type="text" class="form-control" name="lastName" th:value="${employee.getLastName()}">
</div>
<div class="form-group">
<lable>Email</lable>
<input type="email" class="form-control" name="email" th:value="${employee.getEmail()}">
</div>
<div class="form-group">
<lable>Gender</lable>
<div class="form-check form-check-inline">
<input th:checked="${employee.getGender()==1}" class="form-check-input" type="radio" name="gender" value="1">
<lable class="form-check-label">男</lable>
</div>
<div class="form-check form-check-inline">
<input th:checked="${employee.getGender()}" class="form-check-input" type="radio" name="gender" value="0">
<lable class="form-check-label">女</lable>
</div>
</div>
<div class="form-group">
<label>department</label>
<select class="form-control" name="department.id">
<option th:selected="${department.getId()==employee.getDepartment().getId()}" th:each="department:${departments}" th:text="${department.getDepartmentName()}" th:value="${department.getId()}"></option>
</select>
</div>
<div class="form-group">
<label>Birth</label>
<input type="text" class="form-control" name="birth" placeholder="2020-5-22" th:value="${#dates.format(employee.getBirth(),'yyyy-MM-dd HH:mm')}">
</div>
<button type="submit" class="btn btn-primary">修改</button>
</form>