Thymeleaf之字面量、運算符和迭代器

版權聲明:本文爲 小異常 原創文章,非商用自由轉載-保持署名-註明出處,謝謝!
本文網址:https://blog.csdn.net/sun8112133/article/details/107055378







本篇博客主要講解 Thymeleaf 中的 字面量、運算符和迭代器。


一、字面量

字面量 簡單的說就是可以直接寫在表達式中固定的值。

1、文本字面量

<p th:text="'hello world!'"></p>

2、數字字面量

<p th:text="2013"></p>
<p th:text="2013 + 2"></p>

3、布爾字面量

<div th:if="${user.isAdmin()} == false">該用戶不是管理員</div>

4、空值字面量

<div th:if="${user.classes} == null">該學生還沒有班級</div>


二、運算符

Thymeleaf 中也支持一些運算符:算術運算、比較運算、條件運算和無操作運算。

1、算術運算符

+-*/%

<p th:text="2013 + 2"></p>

2、比較運算符

>(gt)<(lt)>=(ge)<=(le)==(eq)!=(ne)

<p th:text="2013 > 2"></p>

3、條件運算符

表達式 ? 值1 : 值2

<p th:text="${age} >= 18 ? '成人' : '未成年'"></p>

4、無操作運算符

_(注意 ?: 之前不能有空格)

<!-- 如果沒有 name 值,則保留標籤內的值 -->
<p th:text="${name} ?: _">默認值</p>


三、迭代器

迭代器 是用來遍歷數組或集合中的數據,相當於 Java 中的 foreach 表達式。

1、基本迭代(th:each)

<body>
	<ul>
		<li th:each="book : ${books}" th:text="${book.name}">Text</li>
	</ul>
</body>

2、狀態變量

狀態變量 主要用於跟蹤迭代器的狀態。

  • index: 索引;
  • count: 當前數量;
  • size: 總數量;
  • current: 當前對象;
  • even: 該元素是否爲奇數;
  • odd: 該元素是否爲偶數;
  • first: 是否爲第一個元素;
  • last: 是否爲最後一個元素。
<body>
	<ul>
		<li th:each="book,status : ${books}" 
			th:text="${book.name} 
				+ ' index:' + ${status.index}
				+ ' count:' + ${status.count}
				+ ' size:' + ${status.size}
				+ ' current:' + ${status.current}
				+ ' even:' + ${status.even}
				+ ' odd:' + ${status.odd}
				+ ' first:' + ${status.first}
				+ ' last:' + ${status.last}
		">Text</li>
	</ul>
</body>

瀏覽器結果



博客中若有不恰當的地方,請您一定要告訴我。前路崎嶇,望我們可以互相幫助,並肩前行!



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章