Thymeleaf基礎語法,寫給想快速開發(搬磚)的後端們

Thymeleaf語法

  1. ${}:訪問thymeleaf命名空間內放着的變量
  2. *{}: 結合${}使用,可以直接去對象屬性,而不用對象名.屬性名,的方式。
  3. #{}: 結合 "th:text"使用,可以獲得服務器內的靜態資源,比如yml文件內定義的一些屬性。或者獲取圖片等資源。
  4. 鏈接URL表達式:@{…}: 它可以連接到目錄下的靜態資源,也可以發起訪問後端。
  5. 常用的對象表達式:“# +靜態方法”。類似java的靜態方法訪問:
#dates: java.util的實用方法。對象:日期格式、組件提取等.
#calendars: 類似於#日期,但對於java.util。日曆對象
#numbers: 格式化數字對象的實用方法。
#strings:字符串對象的實用方法:包含startsWith,/附加等。
#objects: 實用方法的對象。
#bools: 布爾評價的實用方法。
#arrays: 數組的實用方法。
#lists: list集合。
#sets:set集合。
#maps: map集合。
#aggregates: 實用程序方法用於創建聚集在數組或集合.
#messages: 實用程序方法獲取外部信息內部變量表達式,以同樣的方式,因爲他們將獲得使用# {}語法
#ids: 實用程序方法來處理可能重複的id屬性(例如,由於迭代)。
#httpServletRequest:用於web應用中獲取request請求的參數
#session:用於web應用中獲取session的參數
  1. 常用屬性:
th:action 表單提交的地址 <form action="subscribe.html" th:action="@{/subscribe}">
th:each 屬性賦值 <tr th:each="user,userStat:${users}">
th:field 常用於表單字段綁定 <input type="text" value="" th:field="*{username}"></input>
th:href 鏈接地址 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />
th:id 替換id <input th:id="'xxx' + ${collect.id}"/>
th:if 判斷條件 <a th:if="${userId == collect.userId}" >
th:include 佈局標籤,替換內容到引入的文件 <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
th:fragment 佈局標籤,定義代碼片段,其它引用 <div th:fragment="alert">
th:object 替換對象 <div th:object="${session.user}">
th:src 圖片類地址引入 ![](@{/img/logo.png})
th:replace 佈局標籤,替換整個標籤到引入的文件 <div th:replace="fragments/header :: title"></div>
th:text 文本替換 <p th:text="${collect.description}">description
th:value 屬性賦值 <input th:value="${user.name}" />
th:inline 定義js腳本可以使用變量 <script type="text/javascript" th:inline="javascript">
th:remove 刪除某個屬性 <tr th:remove="all">
th:style 設置樣式 th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick 點擊事件 th:οnclick="'getCollect()'"

其中,

  • th:inline 可以讓你的js代碼直接訪問到thymeleaf空間內的對象,很好用。
<script th:inline="javascript">
//提交表單
function form_submit() {
var data={
userId:[[${userId}]], //js引用後端傳來的值
role:[[${role}]],
password:$("#password").val(),
}
$.post("xx",data,function (mes) {
...xxx...
})
  • th:object和th:field:一起用來綁定表單數據。 th:object:用於表單數據對象綁定,將表單綁定到後臺controller的一個JavaBean參數。其實直接name,id之類的,後端也可以反射進行賦值的。
  • th:if:條件判斷。如果爲否則標籤不顯示
  1. 標準表達式
  • 字面:文本文字:放在 單引號 裏面,可以是任意字符,如:‘one text’,‘Another one!’,…
<span th:text="'working web application'">
  • 文字替代: 有兩種方式:一個是|The name is ${name}|,另一個是+號連接:
<span th:text="|Welcome to our application, ${user.name}!|">
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
  1. 運算符:都是雙引號下使用,就會被視爲運算,被單引號括住就作爲字符了。
  • 二元運算符:+,-,*,/,%
  • 布爾運算:and,or,not
  • 比較和相等:>,<,>=,<=(gt,lt,ge,le);==,!=(eq,ne)
  • 條件運算符:IF-THEN: (if) ? (then)

參考

  1. springboot和thymeleaf
  2. springboot和thymeleaf前後端傳值的方法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章