thymeleaf 學習筆記-基礎篇(中文教程)

  (一)Thymeleaf 是個什麼?css

     簡單說, Thymeleaf 是一個跟 Velocity、FreeMarker 相似的模板引擎,它能夠徹底替代 JSP 。相較與其餘的模板引擎,它有以下三個極吸引人的特色:
    1.Thymeleaf 在有網絡和無網絡的環境下皆可運行,即它可讓美工在瀏覽器查看頁面的靜態效果,也可讓程序員在服務器查看帶數據的動態頁面效果。這是因爲它支持 html 原型,而後在 html 標籤裏增長額外的屬性來達到模板+數據的展現方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,因此 thymeleaf 的模板能夠靜態地運行;當有數據返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。
    2.Thymeleaf 開箱即用的特性。它提供標準和spring標準兩種方言,能夠直接套用模板實現JSTL、 OGNL表達式效果,避免天天套模板、該jstl、改標籤的困擾。同時開發人員也能夠擴展和建立自定義的方言。
    3. Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,能夠快速的實現表單綁定、屬性編輯器、國際化等功能。
 (二)應用
  1.簡單的 Thymeleaf 應用
   1)只需加入thymeleaf-2.1.4.RELEASE.jar(http://www.thymeleaf.org/download.html )包,若用maven,則加入以下配置
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>2.1.4</version>
</dependency>
   2)而後增長頭文件(以下)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

      3)就能夠用th標籤動態替換掉靜態數據了。以下圖,後臺傳出的message會將靜態數據「Red Chair」替換掉,若訪問靜態頁面,則顯示數據「Red Chair」。html

<td th:text="${message}">Red Chair</td>

   2.整合springjava

   1)加入thymeleaf-spring4-2.1.4.RELEASE.jar(http://www.thymeleaf.org/download.html )包,若用maven,則加入以下配置jquery

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring3</artifactId>
    <version>2.1.4</version>
</dependency>

   2)在servlet配置文件中加入以下代碼程序員

<!-- Scans the classpath of this application for @Components to deploy as beans -->
       <context:component-scan base-package="com.test.thymeleaf.controller" />

       <!-- Configures the @Controller programming model -->
       <mvc:annotation-driven />

        <!--Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
        <!--springMVC+jsp的跳轉頁面配置-->
       <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
              <!--<property name="prefix" value="/WEB-INF/views/" />-->
              <!--<property name="suffix" value=".jsp" />-->
       <!--</bean>-->

       <!--springMVC+thymeleaf的跳轉頁面配置-->
       <bean id="templateResolver"
          class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
         <property name="prefix" value="/WEB-INF/views/" />
         <property name="suffix" value=".html" />
         <property name="templateMode" value="HTML5" />
       </bean>

       <bean id="templateEngine"
           class="org.thymeleaf.spring4.SpringTemplateEngine">
          <property name="templateResolver" ref="templateResolver" />
       </bean>

       <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
         <property name="templateEngine" ref="templateEngine" />
       </bean>

  3)將靜態頁面加到項目中,更改文件頭,加入th標籤便可。web

 3.th標籤整理spring

  1)簡單表達式express

   --變量表達式  ${……}數組

<input type="text" name="userName" value="James Carrot" th:value="${user.name}" />

    上述代碼爲引用user對象的name屬性值。瀏覽器

     --選擇/星號表達式 *{……}

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

  選擇表達式通常跟在th:object後,直接取object中的屬性。

     --文字國際化表達式  #{……}

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

   調用國際化的welcome語句,國際化資源文件以下

resource_en_US.properties:
home.welcome
=Welcome to here!
resource_zh_CN.properties:

home.welcome=歡迎您的到來!
 
 

   -- URL表達式  @{……}              

<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>
          @{……}支持決定路徑和相對路徑。其中相對路徑又支持跨上下文調用url和協議的引用(//code.jquery.com/jquery-2.0.3.min.js)。
   當URL爲後臺傳出的參數時,代碼以下
<img src="../../static/assets/images/qr-code.jpg" th:src="@{${path}}" alt="二維碼" />

  2)經常使用的th標籤

   --簡單數據轉換(數字,日期)

   <dt>價格</dt>
    <dd th:text="${#numbers.formatDecimal(product.price, 1, 2)}">180</dd>
   <dt>進貨日期</dt>
   <dd th:text="${#dates.format(product.availableFrom, 'yyyy-MM-dd')}">2014-12-01</dd>

   --字符串拼接

<dd th:text="${'$'+product.price}">235</dd>

    --轉義和非轉義文本

    當後臺傳出的數據爲「This is an &lt;em&gt;HTML&lt;/em&gt; text. &lt;b&gt;Enjoy yourself!&lt;/b&gt;」時,若頁面代碼以下則出現兩種不一樣的結果

<div th:text="${html}">
  This is an &lt;em&gt;HTML&lt;/em&gt; text. &lt;b&gt;Enjoy yourself!&lt;/b&gt;
</div> 
<div th:utext="${html}">
  This is an <em>HTML</em> text. <b>Enjoy yourself!</b>
</div>

   --表單中

<form th:action="@{/bb}" th:object="${user}" method="post" th:method="post">

    <input type="text" th:field="*{name}"/>
    <input type="text" th:field="*{msg}"/>

    <input type="submit"/>
</form>

   --顯示頁面的數據迭代

//用 th:remove 移除除了第一個外的靜態數據,用第一個tr標籤進行循環迭代顯示
    <tbody th:remove="all-but-first">
          //將後臺傳出的 productList 的集合進行迭代,用product參數接收,經過product訪問屬性值
                <tr th:each="product:${productList}">
            //用count進行統計,有順序的顯示             <td th:text="${productStat.count}">1</td> <td th:text="${product.description}">Red Chair</td> <td th:text="${'$' + #numbers.formatDecimal(product.price, 1, 2)}">$123</td> <td th:text="${#dates.format(product.availableFrom, 'yyyy-MM-dd')}">2014-12-01</td> </tr> <tr> <td>White table</td> <td>$200</td> <td>15-Jul-2013</td> </tr> <tr> <td>Reb table</td> <td>$200</td> <td>15-Jul-2013</td> </tr> <tr> <td>Blue table</td> <td>$200</td> <td>15-Jul-2013</td> </tr> </tbody>

  --條件判斷

<span th:if="${product.price lt 100}" class="offer">Special offer!</span>

  不能用"<」,">"等符號,要用"lt"等替代

<!-- 當gender存在時,選擇對應的選項;若gender不存在或爲null時,取得customer對象的name-->
<td th:switch="${customer.gender?.name()}">
    <img th:case="'MALE'" src="../../../images/male.png" th:src="@{/images/male.png}" alt="Male" /> <!-- Use "/images/male.png" image -->
    <img th:case="'FEMALE'" src="../../../images/female.png" th:src="@{/images/female.png}" alt="Female" /> <!-- Use "/images/female.png" image -->
    <span th:case="*">Unknown</span>
</td>
<!--在頁面先顯示,而後再在顯示的數據基礎上進行修改-->
<div class="form-group col-lg-6">

<label>姓名<span>&nbsp;</span></label>
  <!--除非resume對象的name屬性值爲null,不然就用name的值做爲placeholder值-->
<input type="text" class="form-control" th:unless="${resumes.name} eq '' or ${resumes.name} eq null"
data-required="true" th:placeholder="${resumes.name}" />
   <!--除非resume對象的name屬性不爲空,不然就定義一個field方便封裝對象,並用placeholder提示-->
<input type="text" th:field="${resume.name}" class="form-control" th:unless="${resumes.name} ne null"
data-required="true" th:placeholder="請填寫您的真實姓名" />
</div>
<!-- 增長class="enhanced"當balance大雨10000 -->
<td th:class="${customer.balance gt 10000} ? 'enhanced'" th:text="${customer.balance}">350</td>

  --根據後臺數據選中select的選項

 

 <div class="form-group col-lg-6">
      <label >性別<span>&nbsp;Sex:</span></label>
      <select th:field="${resume.gender}" class="form-control" th:switch="${resumes.gender.toString()}"
            data-required="true">
              <option value="男" th:case="'男'" th:selected="selected" >男</option>
              <option value="女" th:case="'女'" th:selected="selected" >女</option>
              <option value="">請選擇</option>
      </select>
 </div>

 

  由於gender是定義的Enum(枚舉)類型,因此要用toString方法。用th:switch指定傳出的變量,用th:case對變量的值進行匹配。!"請選擇"放在第一項會出現永遠選擇的是這個選項。或者用th:if

<div class='form-group col-lg-4'>
          <select class='form-control' name="skill[4].proficiency">
                <option >掌握程度</option>
                <option th:if="${skill.level eq '通常'}" th:selected="selected">通常</option>
                 <option th:if="${skill.level eq '熟練'}" th:selected="selected">熟練</option>
                 <option th:if="${skill.level eq '精通'}" th:selected="selected">精通</option>
           </select>
</div>

  --spring表達式語言

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Thymeleaf tutorial: exercise 10</title>
        <link rel="stylesheet" href="../../../css/main-static.css" th:href="@{/css/main.css}" />
        <meta charset="utf-8" />
    </head>
    <body>
        <h1>Thymeleaf tutorial - Solution for exercise 10: Spring Expression language</h1>
  
        <h2>Arithmetic expressions</h2>
        <p class="label">Four multiplied by minus six multiplied by minus two module seven:</p>
        <p class="answer" th:text="${4 * -6 * -2 % 7}">123</p>
 
        <h2>Object navigation</h2>
        <p class="label">Description field of paymentMethod field of the third element of customerList bean:</p>
        <p class="answer" th:text="${customerList[2].paymentMethod.description}">Credit card</p>
 
        <h2>Object instantiation</h2>
        <p class="label">Current time milliseconds:</p>
        <p class="answer" th:text="${new java.util.Date().getTime()}">22-Jun-2013</p>
        
        <h2>T operator</h2>
        <p class="label">Random number:</p>
        <p class="answer" th:text="${T(java.lang.Math).random()}">123456</p>
    </body>
</html>

  --內聯

<label for="body">Message body:</label>
<textarea id="body" name="body" th:inline="text"> Dear [[${customerName}]], it is our sincere pleasure to congratulate your in your birthday: Happy birthday [[${customerName}]]!!! See you soon, [[${customerName}]]. Regards, The Thymeleaf team </textarea>

 --內聯JS <js起止加入以下代碼,不然引號嵌套或者"<"">"等不能用>

/*<![CDATA[*/ …… /*]]>*/

  --js附加代碼:

/*[+ var msg = 'This is a working application'; +]*/

  --js移除代碼:

/*[- */ var msg = 'This is a non-working template'; /* -]*/

 4.不經常使用

  --表達式

   2)文字

            a)文本文字                        'one text','Another one',……
            b)數字文字                        0,34,3.0,12.3,……
            c)布爾文字                        true,flase
            d)空文字                            null
            e)文字標記                         one,sometext,main,……
        3)文本處理
            a)字符串鏈接                       +
            b)文字替換                           | The name id ${name} |        
        4)算術表達式
            a)基本表達式                        +,-,*,/,%
            b)減號(一元運算符)           -
        5)布爾表達式
            a)基本表達式                        and,or
            b)布爾否認(一元運算符)    !,not
        6)比較和相等
            a)比較                                >,<,>=,<=(gt,lt,ge,le)    
            b)相等表達式                       ==,!=(eq,ne)
        7)條件表達式
             a)If-then                            (if) ? (then)
             b)If-then-else                    (if) ? (then) : (else)
             c)Default                           (value) ? : (defaltvalue)           
           全部這些標籤可以結合和嵌套:
              User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

  --表達式基本對象

        在上下文變量評估OGNL表達式時,一些對象表達式可得到更高的靈活性。這些對象將由#號開始引用。
        - #ctx: 上下文對象.
        - #vars: 上下文變量.
        - #locale: 上下文語言環境.
        - #httpServletRequest: (僅在web上文)HttpServletRequest 對象.
        - #httpSession: (僅在web上文)  HttpSession 對象.
      --表達式功能對象
        - #dates:java.util.Date對象的實用方法。 
        - #calendars:和dates相似, 可是 java.util.Calendar 對象.
        - #numbers: 格式化數字對象的實用方法。
        - #strings: 字符創對象的實用方法: contains, startsWith, prepending/appending等.
        - #objects: 對objects操做的實用方法。
        - #bools: 對布爾值求值的實用方法。
        - #arrays: 數組的實用方法。
        - #lists: list的實用方法。
        - #sets: set的實用方法。
        - #maps: map的實用方法。
        - #aggregates: 對數組或集合建立聚合的實用方法。
        - #messages: 在表達式中獲取外部信息的實用方法。
        - #ids: 處理可能重複的id屬性的實用方法 (好比:迭代的結果)。
     --給特定的屬性設值
        下面是用th:action給action設值。
           <form action="subscribe.html" th:action="@{/subscribe}">
        還有不少這樣的屬性,它們每個都針對一個特定的XHTML或者HTML5屬性:
            th:text="${data}"
                將data的值替換該屬性所在標籤的body。字符常量要用引號,好比th:text="'hello world'",th:text="2011+3",th:text="'my name is '+${user.name}"
            th:utext
                和th:text的區別是"unescaped text"。
            th:with
                定義變量,th:with="isEven=${prodStat.count}%2==0",定義多個變量能夠用逗號分隔。
            th:attr
                設置標籤屬性,多個屬性能夠用逗號分隔,好比th:attr="src=@{/image/aa.jpg},title=#{logo}",此標籤不太優雅,通常用的比較少。
            th:[tagAttr]
                設置標籤的各個屬性,好比th:value,th:action等。
                能夠一次設置兩個屬性,好比:th:alt-title="#{logo}"
                   對屬性增長前綴和後綴,用th:attrappend,th:attrprepend,好比:th:attrappend="class=${' '+cssStyle}"
                   對於屬性是有些特定值的,好比checked屬性,thymeleaf都採用bool值,好比th:checked=${user.isActive}
            th:each
                 循環,<tr th:each="user,userStat:${users}">,userStat是狀態變量,有 index,count,size,current,even,odd,first,last等屬性,若是沒有顯示設置狀態變量,    thymeleaf會默 認給個「變量名+Stat"的狀態變量。
            th:if or th:unless
                條件判斷,支持布爾值,數字(非零爲true),字符,字符串等。
            th:switch,th:case
                選擇語句。 th:case="*"表示default case。
相關文章
相關標籤/搜索