1. 程式人生 > >thymeleaf快速入門教程

thymeleaf快速入門教程

thymeleaf教程

本教程涵蓋了常見的前端操作,比如,判斷,迴圈,引入模板,常用函式(日期格式化,字串操作)下拉,js和css中使用,基本可以應對一般場景。

怎麼使用?

前端html頁面標籤中引入如下:

<html xmlns:th="http://www.thymeleaf.org">
  • 1

表示式

  • 簡單表示式 

    • 可用值表示式(後臺設定): ${…}
    • 所有可用值表示式: *{…}

    比如*{name} 從可用值中查詢name,如果有上下文,比如上層是object,則查object中的name屬性。

  • 訊息表示式: #{…} 

    國際化時使用,也可以使用內建的物件,比如date格式化資料

  • 連結表示式: @{…}  用來配合link src href使用的語法
  • 片段表示式: ~{…}  用來引入公共部分程式碼片段,並進行傳值操作使用的語法。
  • 文字

    • 文字: ‘one text’,’another text’,…
    • 數字: 1,2,1.2,…
    • 布林: true,false
    • 空值:null
    • 單詞: something,main,name,…
  • 文字操作

    • 連結:+
    • 替換:|The name is ${name}| html  <a href="" th:href="@{|/name/${test.size()}|}">連結地址:</a>  //渲染後的結果  <a href="/name/3">連結地址:</a> 
  • 數學操作

    • 二元操作:+, - , * , / , %
    • 一元操作: - (負)
  • 布林操作

    • 一元 : and or
    • 二元 : !,not
  • 比較

    • 比較:> , < , >= , <= ( gt , lt , ge , le )
    • 等於:== , != ( eq , ne )
  • 條件

    • If-then: (if) ? (then)
    • If-then-else: (if) ? (then) : (else)
    • Default: (value) ?: (defaultvalue)
  • 無操作  使用_ 來禁止轉義。

支援的操作

html5的操作支援:

th:abbr          th:accept             th:accept-charset
th:accesskey             th:action             th:align
th:alt             th:archive             th:audio
th:autocomplete             th:axis             th:background
th:bgcolor             th:border             th:cellpadding
th:cellspacing             th:challenge             th:charset
th:cite             th:class             th:classid
th:codebase             th:codetype             th:cols
th:colspan             th:compact             th:content
th:contenteditable             th:contextmenu             th:data
th:datetime             th:dir             th:draggable
th:dropzone             th:enctype             th:for
th:form             th:formaction             th:formenctype
th:formmethod             th:formtarget             th:fragment
th:frame             th:frameborder             th:headers
th:height             th:high             th:href
th:hreflang             th:hspace             th:http-equiv

th:icon             th:id             th:inline
th:keytype             th:kind             th:label
th:lang             th:list             th:longdesc
th:low             th:manifest             th:marginheight
th:marginwidth             th:max             th:maxlength
th:media             th:method             th:min
th:name            th:onabort            th:onafterprint
th:onbeforeprint            th:onbeforeunload            th:onblur
th:oncanplay            th:oncanplaythrough            th:onchange
th:onclick            th:oncontextmenu            th:ondblclick
th:ondrag            th:ondragend            th:ondragenter
th:ondragleave            th:ondragover            th:ondragstart
th:ondrop            th:ondurationchange            th:onemptied
th:onended            th:onerror            th:onfocus
th:onformchange            th:onforminput            th:onhashchange
th:oninput            th:oninvalid            th:onkeydown
th:onkeypress            th:onkeyup            th:onload
th:onloadeddata            th:onloadedmetadata            th:onloadstart
th:onmessage            th:onmousedown            th:onmousemove
th:onmouseout            th:onmouseover            th:onmouseup
th:onmousewheel            th:onoffline            th:ononline
th:onpause            th:onplay            th:onplaying
th:onpopstate            th:onprogress            th:onratechange
th:onreadystatechange            th:onredo            th:onreset
th:onresize            th:onscroll            th:onseeked
th:onseeking            th:onselect            th:onshow
th:onstalled            th:onstorage            th:onsubmit
th:onsuspend            th:ontimeupdate            th:onundo
th:onunload            th:onvolumechange            th:onwaiting
th:optimum            th:pattern            th:placeholder
th:poster            th:preload            th:radiogroup
th:rel            th:rev            th:rows
th:rowspan            th:rules            th:sandbox
th:scheme            th:scope            th:scrolling
th:size            th:sizes            th:span
th:spellcheck            th:src            th:srclang
th:standby            th:start            th:step
th:style            th:summary            th:tabindex
th:target            th:title            th:type
th:usemap            th:value            th:valuetype
th:vspace            th:width            th:wrap

th:vspace            th:width            th:wrap
th:xmlbase            th:xmllang            th:xmlspace

布林型別

th:async th:autofocus th:autoplay
th:checked th:controls th:declare
th:default th:defer th:disabled
th:formnovalidate th:hidden th:ismap
th:loop th:multiple th:novalidate
th:nowrap th:open th:pubdate
th:readonly th:required th:reversed
th:scoped th:seamless th:selected

判斷操作

thymeleaf提供了幾種判斷,if、switch

  • 後臺資料
public class TestVo {
    private String name;
    private  Integer Score;
    private  Integer male;
    private Date birthday;

    public TestVo(String name, Integer score, Date birthday, Integer male) {
        this.name = name;
        Score = score;
        this.male = male;
        this.birthday = birthday;
    }
@RequestMapping("/test01")
    public String thymeleaf(ModelMap map){
        List<TestVo> testVos=new ArrayList<>();
        testVos.add(new TestVo("數學",10,new Date(),1));
        testVos.add(new TestVo("數學0001",70,new Date(),2));
        testVos.add(new TestVo("數學01",100,new Date(),3));
        map.put("test",testVos);
        return "/back/import/test";
    }
  • 前端語法
  <table>
       <thead>
           <th></th>
       </thead>
       <tbody>
            <tr th:each="test:${test}">
                <!--判斷成績-->
                <td th:if="${test.Score} gt 0 and ${test.Score} lt 60">差</td>
                <td th:if="${test.Score} ge 60 and ${test.Score} le 70">中</td>
                <td th:if="${test.Score} gt 70 and ${test.Score} le 80">良</td>
                <td th:if="${test.Score} gt 80 and ${test.Score} le 90">優</td>
                <td th:if="${test.Score} gt 90 and ${test.Score} le 100">超級優秀</td>
            </tr>
            <br>
            <tr th:each="test:${test}">
                <!--判斷成績   一般只有兩種情況的時候可以使用這種方式-->
                <td th:if="${test.Score} gt 0 and ${test.Score} lt 60">差</td>
                <!--除了這些條件之外的-->
                <td th:unless="${test.Score} gt 0 and ${test.Score} lt 60">及格</td>
            </tr>
            <tr th:each="test:${test}">
                <td th:switch="${test.male}">
                    <span th:case="1">男</span>
                    <span th:case="2">女</span>
                    <!--其他情況-->
                    <span th:case="*">未知</span>
                </td>
            </tr>

       </tbody>
   </table>
  • 結果

差  中  超級優秀

差  及格  及格

男  女

模板操作

主要引入公共頭部和底部相關程式碼使用 ,當然也可以其他地方使用  - 示例

底部模板程式碼

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<body>
<div th:fragment="footer">
    © 2016 xxx
</div>
</body>
</html>

Springboot整合引入模組

<!--寫入絕對路徑即可引入 -->
<div th:include="/back/import/footer :: footer"></div>

文字和帶格式文字

用來輸入內容到標籤內部,而不是attr中。分為th:text和th:utext兩種,後者可以渲染文字中的標籤。  - th:utext

    map.put("msgutext","<b>1111</b>");
<div th:utext="${msgutext}"></div>

結果:被渲染了

  • th:text
<div th:text="${msgutext}"></div>

結果:原樣輸出到頁面。

外圍包裹–block

有時候需要在程式碼外部加層條件,但寫div之類的又影響樣式,此情況下你可以用下面這種方式:

    <th:block th:with="score=${test.Score}">
        <td th:if="${score} ge 60">及格啦</td>
    </th:block>

迴圈

遍歷元素

  • 示例:
 <tr th:each="test:${test}">
    <td th:text="${test.Score}"></td>
 </tr>

迴圈下標判斷

 List<String> list=new ArrayList<String>();
        list.add("1s");
        list.add("2s");
        list.add("3s");
        map.put("list",list);
<th:block th:each="mylist,iterStat:${list}">
    111
    <span th:text="${mylist}"></span>
        <th:block th:if="${iterStat.index le 1}">
            <span th:text="${mylist}"></span>
        </th:block>
</th:block>

常用操作

  • 日期格式化
 <td th:text="${#dates.format(content.createDate,'yyyy-MM-dd HH:mm:ss')}"  ></td>
  • 字元擷取長度
<td th:if="${#strings.length(content.title) gt 5 } "  th:text="${#strings.substring(content.title,0,5) + '…'}"></td>
  • 下拉選擇
 <select name="subId" id="subId" lay-verify="" >
            <option value="">請選擇</option>
            <option th:each="channelsub:${subchannels}" th:selected="${channelsub.id == subId}"    th:value="${channelsub.id}" th:text="${channelsub.name}"></option>
        </select>

js取值

有時候需要傳遞引數到js中,按如下方式:

  <script th:inline="javascript"  >
        var size= [[${test.size()}]];
        console.info(size)
    </script>
  • 進階  ps: 下面涉及到thymeleaf的語法出,可以替換成其他thymeleaf的語法來用
 <script th:inline="javascript"  >
        //尺寸等於3時列印日誌..
        /*[# th:if="${test.size() eq 3}"]*/
        console.info('Welcome admin');
        /*[/]*/
    </script>

css取值

首先需要後臺設定classname、align的值,之後按如下方式:

<style th:inline="css">
.[[${classname}]] {
text-align: [[${align}]];
}
</style>