Thymeleaf隨記

  • 單純形式

    函數式:${…}

    選擇函數式:*{…}

    消息函數式:#{…}

    鏈接URL函數式:@{…}

  • 常量

  • 字符串常量:'one text' , 'Another one!' ,…

    數字常量:0 , 34 , 3.0 , 12.3 ,…

    布爾常量:true , false

    Null常量:null

    象徵常量:one , sometext , main ,…

  • 文字演算式

    文字列拼接:+

    常量替換:|The name is ${name}|

  • 算數演算式

    二進制演算式:+ , -, * , / , %

    單項目演算式:-

  • 邏輯演算式

    二項目演算式:and , or

    否定演算式:! , not

  • 比較演算式

    比較演算式;> , < , >= , <= ( gt , lt , ge, le )

    等價演算式:== , != ( eq , ne )

  • 條件演算式

    If-then: (if) ? (then)

    If-then-else: (if) ? (then) : (else)

    Default: (value) ?: (defaultvalue)

    例:

'User is of type ' + (${user.isAdmin()} ?  'Administrator' : (${user.type} ?: 'Unknown'))

消息的形式#{...},基於以下的消息書寫格式

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

以下的鏈接文件必須

home.welcome=Bienvenido anuestra tienda de comestibles!

但是沒有考慮帶有參數的消息,比如,web應用中需要顯示誰訪問網站,並且在其下打出歡迎標語,可以向下面這樣:

<p>Bienvenidoa nuestra tienda de comestibles, John Apricot!</p>

最終,消息中存在參數的時候:

home.welcome=Bienvenido anuestra tienda de comestibles, {0}!

參數遵從java.text.MessageFormat的標準格式,根據其他類的API的文檔,可以指定數值類型和時間類型Httpsession存在有user的參數時,可以按照以下的書寫格式表示:

<p th:utext="#{home.welcome(${session.user.name})}"> Welcome to our grocery store, SebastianPepper!</p>

多個參數可以用逗點分割,如下:

<p th:utext="#{${welcomeMsgKey}(${session.user.name})}"> Welcome to our grocery store, SebastianPepper!</p>

變量的形式${...}實際上是,上下文中的變量通過map實施,OGNL(Object-Graph Navigation Language)

以下是OGNL的語法:

<p>Todayis: <span th:text="${today}">13february 2011</span>.</p>

上面的內容實際上和以下的內容同等:

ctx.getVariables().get("today");

但是使用OGNL更加強健,如下:

<p th:utext="#{home.welcome(${session.user.name})}"> Welcome to our grocery store, SebastianPepper!</p>

事實上是通過以下的方法取得user

((User)ctx.getVariables().get("session").get("user")).getName();

通過OGNL的功能取得變量值的方法不止一種:

/*

  • 通過使用逗點取得屬性,和通過Getter方法取得屬性是相同的

     */

    ${person.father.name}

    /*

  • 通過使用([])可以取得指定的屬性

  • 取得指定變量的屬性,在([])記入字符串

     */

    ${person['father']['name']}

    /*

  • 對象是map的時候使用逗點和使用get(...)方法相同

     */

    ${countriesByCode.ES}

    ${personsByName['Stephen Zucchini'].age}

    /*

  • 數組或者是集合的時候同樣可以使用([])的方法記入下標

     */

    ${personsArray[0].name}

    /*

  • 可以調用方法,可以有參數

     */

    ${person.createCompleteName()}

    ${person.createCompleteNameWithSeparator('-')}

使用OGNL表達式時的上下文對象:

  • #vars:上下文變量

  • #locale :上下文本地變量

  • #httpServletRequest : (web上下文) HttpServletRequest對象

  • #httpSession : (web上下文) HttpSession對象

可以像下面這樣:

Established locale country:<span th:text="${#locale.country}">US</span>.

Utility對象

基本的對象以外,還提供通用的Utility對象。

  • #dates : java.util.Date對應的方法: format、component

  • #calendars : #dates相似java.util.Calendar對象用

  • #numbers : 數字對應的方法

  • #strings : String對象對應的方法:contains, startsWith, prepending/appending,

  • #objects : object對應的方法

  • #bools :布爾值對應的方法

  • #arrays :數組對應的方法

  • #lists : list對應的方法

  • #sets : set對應的方法

  • #maps : map對應的方法

  • #aggregates:數組和集合對應的方法

  • #messages: #{…}一樣,對應其#{…}的抽出方法。

  • #ids : 通過循環處理,取得id的方法。

<p>

  Today is: <span th:text="${#calendars.format(today,'ddMMMM yyyy')}">13 May 2011</span>

</p>

變量表達式不僅有${...},也可以書寫成*{...},重要的不同是,*表達式不是對應上下文變量的map,是對應已經選擇的對象。如果沒有已選擇對象,$表達式和*表達式完全一樣。對象的選擇是什麼?是th:object,自定義對象。

通過使用( userprofile.html )

  <div th:object="${session.user}">

    <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>

    <p>Surname:<span th:text="*{lastName}">Pepper</span>.</p>

    <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>

  </div>

以下的完全一樣:

<div>

  <p>Name:<span th:text="${session.user.firstName}">Sebastian</span>.</p>

  <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>

  <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>

</div>

$表達式和*表達式可以同使用:

<div th:object="${session.user}">

  <p>Name: <spanth:text="*{firstName}">Sebastian</span>.</p>

  <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>

  <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>

</div>

通過$表達式可以使用#object變量選擇對象屬性:

<div th:object="${session.user}">

  <p>Name: <spanth:text="${#object.firstName}">Sebastian</span>.</p>

  <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>

  <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>

</div>

循環的時候,object變量不能選擇的時候,$表達式和*表達式完全一

<div>

  <p>Name: <spanth:text="*{session.user.name}">Sebastian</span>.</p>

  <p>Surname: <span th:text="*{session.user.surname}">Pepper</span>.</p>

  <p>Nationality: <span th:text="*{session.user.nationality}">Saturn</span>.</p></div>

變量的形式@{...},對應URL存在以下形式:

  • 絕對URL: http://www.thymeleaf.org

  • 相對URL:

  • Page相對URL: user/login.html

  • 上下文相對URL: /itemdetails?id=3 (service內的上下文自動賦予)

  • Service相對URL: ~/billing/processInvoice (相同的service內可以調用不相同的上下文 (= application)的URL)

  • 協議相對URL: //code.jquery.com/jquery-2.0.3.min.js

Thymeleaf中可以使用對於URL相對的URL的時候IWebContext的上下文對象需要被實現使用其相上下文對象時,可以取得在httprequest內生成相對應的相對路徑鏈接信息

使用th:href :

<!-- Will produce'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) -->

<a href="details.html"th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}"></a>

<!-- Will produce'/gtvg/order/details?orderId=3' (plus rewriting) -->

<a href="details.html"th:href="@{/order/details(orderId=${o.id})}"></a>

<!-- Will produce'/gtvg/order/3/details' (plus rewriting) -->

<a href="details.html"th:href="@{/order/{orderId}/details(orderId=${o.id})}"></a>

 

以下幾點注意:

  • th:href是改變屬性用的屬性: 設定生成<a>標籤的href屬性的鏈接URL

  • URL的參數可以指定 ( orderId=${o.id}的部分)自動的編程進去

  • 多個參數指定的時候,可以使用都好分割@{/order/process(execId=${execId},execType='FAST')}

  • URL路徑內可以使用變量@{/order/{orderId}/details(orderId=${orderId})}

  • /開始是相對URL( /order/details ),自動的在應用前面補充上去

  • 不使用cookie時,或者不知道的時候把";jsessionid=..."追加在對應的URL後面。使用cookie的時候調用URL RewritingThymeleaf對應全部的URL

  • 使用Servlet APIresponse.encodeURL(...)的結構,需要單獨追加lib文件

  • 使用th:href 標籤的時候,可以指定任意的href屬性,這樣可以直接通過瀏覽器打開文件。

  • 消息表達式 ( #{...} )同樣可以使用URL鏈接形式。

<a th:href="@{${url}(orderId=${o.id})}">view</a>

<a th:href="@{'/details/'+${user.login}(orderId=${o.id})}">view</a>

  • 字符串常量

    字符串常量是在單引號(’’)範圍中的,什麼文字都可以,使用\'轉義單引號。

<p>

  Now you are looking at a <span th:text="'workingweb application'">templatefile</span>.

</p>

  • 數值常量

    數字常量就是那樣表示就可以。

<p>Theyear is <span th:text="2013">1492</span>.</p>

<p>Intwo years, it will be <spanth:text="2013+ 2">1494</span>.</p>

  • 布爾常量

    布爾常量是truefalse

<div th:if="${user.isAdmin()}== false"> ...

需要注意的是==false是在}的外面,這種時候,使用的是Thymeleaf自己的引擎處理。如果==false是在}的裏面,使用的是OGNL/SpringEL引擎處理

<div th:if="${user.isAdmin()== false}">...

  • Null常量

    可以使用null常量

<div th:if="${variable.something} == null"> ...

  • Token常量

    數值常量,布爾常量,null常量是token常量的特殊形式。Token常量是單純的語法,和字符串常量( '...' )一樣,因爲文字 ( A-Z and a-z ),數字 ( 0-9 ),括號 ( [] ), 句點是( . ), 橫線是( - ) ,下劃線是( _ )。所以寫成以下的形式:

<div th:class="'content'">...</div>

也可以寫成以下的形式:

div th:class="content">...</div>

字符串拼接是通過+演算式來實現的。字符串常量,值或者是消息文本都可以拼接:

th:text="'The name ofthe user is ' + ${user.name}"

因爲使用常量替換使得format變得簡單。'...' +'...'的形式就沒有必要了。

常量替換的時候,替換範圍使用豎線 ( | ):

<span th:text="|Welcometo our application, ${user.name}!|">

這和以下的方法相同:

<span th:text="'Welcometo our application, ' + ${user.name} + '!'">

常量替換的時候,也可以和其他的表達式混合使用:

<span th:text="${onevar}+ '' + |${twovar}, ${threevar}|">

注意點,常量替換要在( |...| )內使用,表達式只可以是${...},其他的常量( '...' )或者是布爾值,數值token或者是條件表達式是不可以使用的。

可以使用的演算式+ , - , * , / , %

th:with="isEven=(${prodStat.count}% 2 == 0)"

這個演算式也可以使用OGNL表達式:

th:with="isEven=${prodStat.count% 2 == 0}"

可替代演算式: div ( / ), mod ( % )

可以使用的演算式> , < , >= , <===!=但是在xml的屬性中<>不可以使用的時候,需要用&lt;&gt;代替使用。

th:if="${prodStat.count}&gt; 1" th:text="'Execution mode is ' + ( (${execMode} == 'dev')?'Development' : 'Production')"

可替代演算式: gt ( > ), lt ( < ), ge ( >= ), le ( <= ), not ( ! ), eq ( == ), neq / ne ( != )

<tr th:class="${row.even}?'even' : 'odd'">……</tr>

條件演算式的三個部分( condition, then and else ),在式中可以使用( ${...} , *{...} ) ( #{...} )URL( @{...} ) ( '...' )

< tr th:class="${row.even}?(${row.first}? 'first' : 'even') : 'odd'">……</tr>

Else可以省略

< tr th:class="${row.even}?'alt'">……</tr>

默認演算式是then沒有的特別條件。兩個表達式最初的值爲null的時候:

< div th:object="${session.user}">……

<p>Age:<span th:text="*{age}?: '(no age specified)'">27</span>.</p>

</ div >

年齡爲null的時候和以下的方法相同:

< div th:object="${session.user}">……

<p>Age:<span th:text="*{age != null}? *{age} : '(no age specified)'">27</span>..</p>

</ div >

寫在括號中是可以的:

<p>

  Name:

  <spanth:text="*{firstName}?:(*{admin}? 'Admin' : #{default.username})">Sebastian</span>

</p>

 

 


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