springboot中 thymeleaf 的基础用法

上一节上已经讲了springboot 与 thymeleaf 的集成和thymeleaf的页面布局,本节将介绍thymeleaf的一些基础用法。

首先一切当然以官方文档为参考,文档地址:

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

在使用的页面头部定义thymeleaf的命名空间 th:*。

<html xmlns:th="http://www.thymeleaf.org">

1.取值方式

Thymeleaf允许您指定文本应与特定的消息对应。#{...}语法

<p th:text="#{home.welcome}">Welcome to our grocery store!</p>

 <p  class="pl-2 pr-2 pt-1 pb-1 mr-3 border " th:text="${student.studentName}">

<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>

<p>The message is "[(${msg})]"</p> 内联表达式 
对应  <p>The message is "[[${msg}]]"</p>
这里注意:th:utext 与 th:text 区别在于th:text 会对文本内容中的标签进行转移处理。<br> -->  &lt;/b&gt;
同时 [[...]] 对应于 th:text (即结果将是HTML-转义), [(...)] 对应于 th:utext 并且不会执行任何HTML转义。

2. 循环 th:each、

  • 迭代指数,从0开始。这是index财产。
  • 迭代指数,从1开始。这是count财产。
  • 迭代变量中元素的总数。这是size财产。
  • 这个ITER变量每次迭代。这是current财产。
  • 当前的迭代是偶数还是奇数。这些是even/odd布尔属性
  • 当前的迭代是否是第一次。这是first布尔属性
  • 当前的迭代是否是最后一次迭代。这是last布尔属性
 <option th:each="subCampusDTO : ${subCampusDTOList}" th:value="${subCampusDTO.subCampusId}" 
th:text="${subCampusDTO.subCampusName}"> </option>

<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  </tr>

3.判断  th:if、 th:unless、th:switch

注意,th:if属性将不仅计算布尔型条件。它的功能超出了这一点,它将计算指定的表达式为true遵循这些规则:

  • 如果值不是NULL:
    • 如果值是布尔值,并且是true.
    • 如果值是一个数字,并且是非零的。
    • 如果值是一个字符,并且是非零的。
    • 如果值是字符串,而不是“false”、“off”或“no”
    • 如果值不是布尔值、数字、字符或字符串。
  • (如果值为NULL,则th:if将计算为false)。

th:if 的与 th:unless 的作用同 一般的if else

<a href="comments.html"
   th:href="@{/product/comments(prodId=${prod.id})}" 
   th:if="${#lists.isEmpty(prod.comments)}">view</a> 

<a href="comments.html"
   th:href="@{/product/comments(prodId=${prod.id})}" 
   th:if="${not #lists.isEmpty(prod.comments)}">view</a> 
等于
<a href="comments.html"
   th:href="@{/comments(prodId=${prod.id})}" 
   th:unless="${#lists.isEmpty(prod.comments)}">view</a>



<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  //默认选项指定为th:case="*"
  <p th:case="*">User is some other thing</p>
</div>

4.事件属性 th:onclick

<button type="button"  th:onclick="addFlStudent([[$(student.studentId)]])" th:text="添加"></button>

以上这些都是最基本的一些操纵写法。有其他的操作可参考官方文档。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值