Thymeleaf 标签学习 之 th:with 的使用

一、标签含义

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();
   }
}

微笑是人类最好的名片,一个懂得微笑的人,生活中一定是一个快乐的人。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值