一、标签含义
th:with用于定义局部变量。其作用范围在其所在标签或者子标签中有效
变量在其所在标签中使用
Hello,<span th:with="name='二狗子'" th:text="${name}"></span>
变量在子标签中使用
<ul th:with="liSize=5">
<li th:each="index : ${#numbers.sequence(1, liSize)}" >[(${index})]. </li>
</ul>
可一次定义多个,逗号分隔
<div th:with="firstBean=${list[0]}">
<p>Da jia yi qi lai huan ying <span th:text="${firstBean.userName}"></span>.</p>
</div>
<div th:with="firstBean=${list[0]},secondBean=${list[1]}">
<p>Da jia yi qi lai huan ying <span th:text="${firstBean.userName}"></span>.</p>
<p> he <span th:text="${secondBean.userName}"></span>.</p>
</div>
可复用
<div th:with="nameStr=${userBean.name},role=${roles[nameStr]}">
<div th:text="${nameStr}"></div>
<div th:text="${role}"></div>
</div>
二、标签使用方法
第一种:前端直接调用后端Service服务
<li>
<p>测试类型:</p>
<select name="status" th:with="testType=${@test.getTestType()}">
<option value="">请选择</option>
<option th:each="t : ${testType}" th:text="${t.testTypeName}" th:value="${t.testTypeId}"></option>
</select>
</li>
@Service("test")
public class TestService {
@Resource
private TestDao testDao;
public List<TestBean> getTestType() {
return testDao.getTestType();
}
}
注意!!! 注意!!! 注意!!!
@后的服务名 要跟@service中一致(如test)
第二种:前端直接调用Controller层声明的Service服务
<li>
<p>测试类型:</p>
<select name="status" th:with="testType=${@testService.getTestType()}">
<option value="">请选择</option>
<option th:each="t : ${testType}" th:text="${t.testTypeName}" th:value="${t.testTypeId}"></option>
</select>
</li>
@Controller
public class TestController{
@Resource
private TestService testService ;
@GetMapping("/getTestType")
@ResponseBody
public List<TestBean> getTestType() {
return testService .getTestType();;
}
}
@Service
public class TestService {
@Resource
private TestDao testDao;
public List<TestBean> getTestType() {
return testDao.getTestType();
}
}