一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|編程技術|正則表達式|

服務器之家 - 編程語言 - JAVA教程 - springboot中thymeleaf模板使用詳解

springboot中thymeleaf模板使用詳解

2020-09-24 15:57純潔的蟲子 JAVA教程

這篇文章將更加全面詳細的介紹thymeleaf的使用。thymeleaf 是新一代的模板引擎,在spring4.0中推薦使用thymeleaf來做前端模版引擎。

這篇文章將更加全面詳細的介紹thymeleaf的使用。thymeleaf 是新一代的模板引擎,在spring4.0中推薦使用thymeleaf來做前端模版引擎。

thymeleaf介紹

簡單說, Thymeleaf 是一個跟 Velocity、FreeMarker 類似的模板引擎,它可以完全替代 JSP 。相較與其他的模板引擎,它有如下三個極吸引人的特點:

1.Thymeleaf 在有網(wǎng)絡和無網(wǎng)絡的環(huán)境下皆可運行,即它可以讓美工在瀏覽器查看頁面的靜態(tài)效果,也可以讓程序員在服務器查看帶數(shù)據(jù)的動態(tài)頁面效果。這是由于它支持 html 原型,然后在 html 標簽里增加額外的屬性來達到模板+數(shù)據(jù)的展示方式。瀏覽器解釋 html 時會忽略未定義的標簽屬性,所以 thymeleaf 的模板可以靜態(tài)地運行;當有數(shù)據(jù)返回到頁面時,Thymeleaf 標簽會動態(tài)地替換掉靜態(tài)內(nèi)容,使頁面動態(tài)顯示。

2.Thymeleaf 開箱即用的特性。它提供標準和spring標準兩種方言,可以直接套用模板實現(xiàn)JSTL、 OGNL表達式效果,避免每天套模板、該jstl、改標簽的困擾。同時開發(fā)人員也可以擴展和創(chuàng)建自定義的方言。

3.Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,可以快速的實現(xiàn)表單綁定、屬性編輯器、國際化等功能。

標準表達式語法

它們分為四類:

1.變量表達式
2.選擇或星號表達式
3.文字國際化表達式
4.URL表達式

變量表達式

變量表達式即OGNL表達式或Spring EL表達式(在Spring術語中也叫model attributes)。如下所示: ${session.user.name}

它們將以HTML標簽的一個屬性來表示:

?
1
2
<span th:text="${book.author.name}">
<li th:each="book : ${books}">

選擇(星號)表達式

選擇表達式很像變量表達式,不過它們用一個預先選擇的對象來代替上下文變量容器(map)來執(zhí)行,如下: *{customer.name}

被指定的object由th:object屬性定義:

?
1
2
3
4
5
<div th:object="${book}">
 ...
 <span th:text="*{title}">...</span>
 ...
</div>

文字國際化表達式

文字國際化表達式允許我們從一個外部文件獲取區(qū)域文字信息(.properties),用Key索引Value,還可以提供一組參數(shù)(可選).

?
1
2
#{main.title}
#{message.entrycreated(${entryId})}

可以在模板文件中找到這樣的表達式代碼:

?
1
2
3
4
5
6
<table>
 ...
 <th th:text="#{header.address.city}">...</th>
 <th th:text="#{header.address.country}">...</th>
 ...
</table>

URL表達式

URL表達式指的是把一個有用的上下文或回話信息添加到URL,這個過程經(jīng)常被叫做URL重寫。
@{/order/list}

URL還可以設置參數(shù):

@{/order/details(id=${orderId})}

相對路徑:

@{../documents/report}

讓我們看這些表達式:

?
1
2
<form th:action="@{/createOrder}">
<a href="main.html" rel="external nofollow" th:href="@{/main}" rel="external nofollow" >

變量表達式和星號表達有什么區(qū)別嗎?

如果不考慮上下文的情況下,兩者沒有區(qū)別;星號語法評估在選定對象上表達,而不是整個上下文

什么是選定對象?就是父標簽的值,如下:

?
1
2
3
4
5
<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>

這是完全等價于:

?
1
2
3
4
5
<div th:object="${session.user}">
  <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>

當然,美元符號和星號語法可以混合使用:

?
1
2
3
4
5
<div th:object="${session.user}">
  <p>Name: <span th: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>

表達式支持的語法

字面(Literals)

  1. 文本文字(Text literals): 'one text', 'Another one!',…
  2. 數(shù)字文本(Number literals): 0, 34, 3.0, 12.3,…
  3. 布爾文本(Boolean literals): true, false
  4. 空(Null literal): null
  5. 文字標記(Literal tokens): one, sometext, main,…

文本操作(Text operations)

  1. 字符串連接(String concatenation): +
  2. 文本替換(Literal substitutions): |The name is ${name}|

算術運算(Arithmetic operations)

  1. 二元運算符(Binary operators): +, -, *, /, %
  2. 減號(單目運算符)Minus sign (unary operator): -

布爾操作(Boolean operations)

  1. 二元運算符(Binary operators):and, or
  2. 布爾否定(一元運算符)Boolean negation (unary operator):!, not

比較和等價(Comparisons and equality)

  1. 比較(Comparators): >, <, >=, <= (gt, lt, ge, le)
  2. 等值運算符(Equality operators):==, != (eq, ne)

條件運算符(Conditional operators)

  1. If-then: (if) ? (then)
  2. If-then-else: (if) ? (then) : (else)
  3. Default: (value) ?: (defaultvalue)

所有這些特征可以被組合并嵌套:

 

復制代碼 代碼如下:

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

 

常用th標簽都有那些?

 

    <s id="2ycig"></s>
  • <dl id="2ycig"><dd id="2ycig"></dd></dl>
    <kbd id="2ycig"><table id="2ycig"></table></kbd>
      <abbr id="2ycig"><menu id="2ycig"></menu></abbr>
        關鍵字 功能介紹 案例
        th:id 替換id <input th:id="'xxx' + ${collect.id}"/>
        th:text 文本替換 <p th:text="${collect.description}">description</p>
        th:utext 支持html的文本替換 <p th:utext="${htmlcontent}">conten</p>
        th:object 替換對象 <div th:object="${session.user}">
        th:value 屬性賦值 <input th:value="${user.name}" />
        th:with 變量賦值運算 <div th:with="isEven=${prodStat.count}%2==0"></div>
        th:style 設置樣式 th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
        th:onclick 點擊事件 th:onclick="'getCollect()'"
        th:each 屬性賦值 tr th:each="user,userStat:${users}">
        th:if 判斷條件 <a th:if="${userId == collect.userId}" >
        th:unless 和th:if判斷相反 <a th:href="@{/login}" rel="external nofollow" rel="external nofollow" rel="external nofollow" th:unless=${session.user != null}>Login</a>
        th:href 鏈接地址 <a th:href="@{/login}" rel="external nofollow" rel="external nofollow" rel="external nofollow" th:unless=${session.user != null}>Login</a> />
        th:switch 多路選擇 配合th:case 使用 <div th:switch="${user.role}">
        th:case th:switch的一個分支 <p th:case="'admin'">User is an administrator</p>
        th:fragment 布局標簽,定義一個代碼片段,方便其它地方引用 <div th:fragment="alert">
        th:include 布局標簽,替換內(nèi)容到引入的文件 <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
        th:replace 布局標簽,替換整個標簽到引入的文件 <div th:replace="fragments/header :: title"></div>
        th:selected selected選擇框 選中 th:selected="(${xxx.id} == ${configObj.dd})"
        th:src 圖片類地址引入 <img class="img-responsive" xhtml" id="highlighter_995163">
        ?
        1
        2
        <p th:text="${collect.description}">description</p>
        <span th:text="'Welcome to our application, ' + ${user.name} + '!'">

        字符串拼接還有另外一種簡潔的寫法

        ?
        1
        <span th:text="|Welcome to our application, ${user.name}!|">

        2、條件判斷 If/Unless

        Thymeleaf中使用th:if和th:unless屬性進行條件判斷,下面的例子中,<a>標簽只有在th:if中條件成立時才顯示:

        ?
        1
        2
        <a th:if="${myself=='yes'}" > </i> </a>
        <a th:unless=${session.user != null} th:href="@{/login}" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Login</a>

        th:unless于th:if恰好相反,只有表達式中的條件不成立,才會顯示其內(nèi)容。

        也可以使用 (if) ? (then) : (else) 這種語法來判斷顯示的內(nèi)容

        3、for 循環(huán)

        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        <tr th:each="collect,iterStat : ${collects}">
          <th scope="row" th:text="${collect.id}">1</th>
          <td >
           <img th:src="${collect.webLogo}"/>
          </td>
          <td th:text="${collect.url}">Mark</td>
          <td th:text="${collect.title}">Otto</td>
          <td th:text="${collect.description}">@mdo</td>
          <td th:text="${terStat.index}">index</td>
        </tr>

        iterStat稱作狀態(tài)變量,屬性有:

        1. index:當前迭代對象的index(從0開始計算)
        2. count: 當前迭代對象的index(從1開始計算)
        3. size:被迭代對象的大小
        4. current:當前迭代變量
        5. even/odd:布爾值,當前循環(huán)是否是偶數(shù)/奇數(shù)(從0開始計算)
        6. first:布爾值,當前循環(huán)是否是第一個
        7. last:布爾值,當前循環(huán)是否是最后一個

        4、URL

        URL在Web應用模板中占據(jù)著十分重要的地位,需要特別注意的是Thymeleaf對于URL的處理是通過語法@{…}來處理的。
        如果需要Thymeleaf對URL進行渲染,那么務必使用th:href,th:src等屬性,下面是一個例子

        ?
        1
        2
        3
        4
        5
        <!-- Will produce 'http://localhost:8080/standard/unread' (plus rewriting) -->
         <a th:href="@{/standard/{type}(type=${type})}" rel="external nofollow" >view</a>
         
        <!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
        <a href="details.html" rel="external nofollow" th:href="@{/order/{orderId}/details(orderId=${o.id})}" rel="external nofollow" >view</a>

        設置背景

         

        復制代碼 代碼如下:

        <div th:style="'background:url(' + @{/<path-to-image>} + ');'"></div>

         

        根據(jù)屬性值改變背景

         

        復制代碼 代碼如下:

         <div class="media-object resource-card-image"  th:style="'background:url(' + @{(${collect.webLogo}=='' ? 'img/favicon.png' : ${collect.webLogo})} + ')'" ></div>

         

        幾點說明:

        1. 上例中URL最后的(orderId=${o.id}) 表示將括號內(nèi)的內(nèi)容作為URL參數(shù)處理,該語法避免使用字符串拼接,大大提高了可讀性
        2. @{...}表達式中可以通過{orderId}訪問Context中的orderId變量
        3. @{/order}是Context相關的相對路徑,在渲染時會自動添加上當前Web應用的Context名字,假設context名字為app,那么結果應該是/app/order

        5、內(nèi)聯(lián)js

        內(nèi)聯(lián)文本:[[…]]內(nèi)聯(lián)文本的表示方式,使用時,必須先用th:inline=”text/JavaScript/none”激活,th:inline可以在父級標簽內(nèi)使用,甚至作為body的標簽。內(nèi)聯(lián)文本盡管比th:text的代碼少,不利于原型顯示。

        ?
        1
        2
        3
        4
        5
        6
        7
        8
        <script th:inline="javascript">
        /*<![CDATA[*/
        ...
        var username = /*[[${sesion.user.name}]]*/ 'Sebastian';
        var size = /*[[${size}]]*/ 0;
        ...
        /*]]>*/
        </script>

        js附加代碼:

        ?
        1
        2
        3
        /*[+
        var msg = 'This is a working application';
        +]*/

        js移除代碼:

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

        6、內(nèi)嵌變量

        為了模板更加易用,Thymeleaf還提供了一系列Utility對象(內(nèi)置于Context中),可以通過#直接訪問:

        1. dates : java.util.Date的功能方法類。
        2. calendars : 類似#dates,面向java.util.Calendar
        3. numbers : 格式化數(shù)字的功能方法類
        4. strings : 字符串對象的功能類,contains,startWiths,prepending/appending等等。
        5. objects: 對objects的功能類操作。
        6. bools: 對布爾值求值的功能方法。
        7. arrays:對數(shù)組的功能類方法。
        8. lists: 對lists功能類方法
        9. sets
        10. maps

        下面用一段代碼來舉例一些常用的方法:

        dates

        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        /*
         * Format date with the specified pattern
         * Also works with arrays, lists or sets
         */
        ${#dates.format(date, 'dd/MMM/yyyy HH:mm')}
        ${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}
        ${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}
        ${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}
         
        /*
         * Create a date (java.util.Date) object for the current date and time
         */
        ${#dates.createNow()}
         
        /*
         * Create a date (java.util.Date) object for the current date (time set to 00:00)
         */
        ${#dates.createToday()}

        strings

        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        /*
         * Check whether a String is empty (or null). Performs a trim() operation before check
         * Also works with arrays, lists or sets
         */
        ${#strings.isEmpty(name)}
        ${#strings.arrayIsEmpty(nameArr)}
        ${#strings.listIsEmpty(nameList)}
        ${#strings.setIsEmpty(nameSet)}
         
        /*
         * Check whether a String starts or ends with a fragment
         * Also works with arrays, lists or sets
         */
        ${#strings.startsWith(name,'Don')}         // also array*, list* and set*
        ${#strings.endsWith(name,endingFragment)}      // also array*, list* and set*
         
        /*
         * Compute length
         * Also works with arrays, lists or sets
         */
        ${#strings.length(str)}
         
        /*
         * Null-safe comparison and concatenation
         */
        ${#strings.equals(str)}
        ${#strings.equalsIgnoreCase(str)}
        ${#strings.concat(str)}
        ${#strings.concatReplaceNulls(str)}
         
        /*
         * Random
         */
        ${#strings.randomAlphanumeric(count)}

        使用thymeleaf布局

        使用thymeleaf布局非常的方便

        定義代碼片段

        ?
        1
        2
        3
        <footer th:fragment="copy">
        &copy; 2016
        </footer>

        在頁面任何地方引入:

        ?
        1
        2
        3
        4
        <body>
         <div th:include="footer :: copy"></div>
         <div th:replace="footer :: copy"></div>
         </body>

        th:include 和 th:replace區(qū)別,include只是加載,replace是替換

        返回的HTML如下:

        ?
        1
        2
        3
        4
        <body>
          <div> &copy; 2016 </div>
         <footer>&copy; 2016 </footer>
        </body>

        下面是一個常用的后臺頁面布局,將整個頁面分為頭部,尾部、菜單欄、隱藏欄,點擊菜單只改變content區(qū)域的頁面

        ?
        1
        2
        3
        4
        5
        6
        7
        8
        9
        <body class="layout-fixed">
         <div th:fragment="navbar" class="wrapper" role="navigation">
          <div th:replace="fragments/header :: header">Header</div>
          <div th:replace="fragments/left :: left">left</div>
          <div th:replace="fragments/sidebar :: sidebar">sidebar</div>
          <div layout:fragment="content" id="content" ></div>
          <div th:replace="fragments/footer :: footer">footer</div>
         </div>
        </body>

        任何頁面想使用這樣的布局值只需要替換中見的 content模塊即可

        ?
        1
        2
        3
        4
        <html xmlns:th="http://www.thymeleaf.org" layout:decorator="layout">
         <body>
          <section layout:fragment="content">
         ...

        也可以在引用模版的時候傳參

        ?
        1
        <head th:include="layout :: htmlhead" th:with="title='Hello'"></head>

        layout 是文件地址,如果有文件夾可以這樣寫 fileName/layout:htmlhead

        htmlhead 是指定義的代碼片段 如 th:fragment="copy"

        源碼案例

        這里有一個開源項目幾乎使用了這里介紹的所有標簽和布局,大家可以參考:cloudfavorites

        以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

        原文鏈接:http://blog.csdn.net/ityouknow/article/details/52441288

        延伸 · 閱讀

        精彩推薦
        主站蜘蛛池模板: 欧美亚洲第一区 | 青青青在线视频播放 | 久久99视热频国只有精品 | 国产精品福利在线观看免费不卡 | 亚洲日日操 | 男男羞羞视频网站国产 | 免费视频一区 | 91麻豆国产精品91久久久 | 天美传媒tm0087 | 99久久精品无码一区二区毛片 | 欧美视频一区二区专区 | 2022国产麻豆剧果冻传媒入口 | 99在线观看视频 | 免费观看成年肉动漫网站 | 双性肉文h | 四虎院影永久在线观看 | heyzo1754北岛玲在线视频 | 美女脱了内裤让男生玩屁股 | 婷婷九月| 久久久久久久国产精品视频 | 黑人与老女人做受 | 国产清纯女高中生在线观看 | 日韩欧美一区二区三区中文精品 | 国产日韩视频一区 | 鬼吹灯天星术在线高清观看 | 农夫成人网 | 扒开黑女人p大荫蒂老女人 扒开大腿狠狠挺进视频 | crdy在线看亚洲 | 国产成人lu在线视频 | 免费又爽又黄禁片视频在线播放 | 91制片厂果冻传媒首页 | 99成人免费视频 | 久久婷婷丁香五月色综合啪免费 | 亚洲欧美专区 | 黑人k8经典| 午夜剧场1000 | 色综合欧美色综合七久久 | 日韩精品成人在线 | 久久人妻熟女中文字幕AV蜜芽 | 999国产精品亚洲77777 | 国产第一草草影院 |