1. 程式人生 > >SpringBoot2.0Web開發例項(二)Thymeleaf模板引擎

SpringBoot2.0Web開發例項(二)Thymeleaf模板引擎

本文作者:Spring_ZYL
意見反饋:[email protected]
文章來源:https://blog.csdn.net/gozhuyinglong
版權宣告:本文版權歸作者所有,轉載請註明出處

一、引入Thymeleaf依賴

在pom檔案中新增如下內容

            <!--引入thymeleaf模板引擎-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId
>
spring-boot-starter-thymeleaf</artifactId> </dependency>

二、簡單例項

Thymelea會自動渲染classpath:/templates/下的檔案,我們將html檔案放入,即可使用

Controller程式碼如下:

    package com.zyl.springboot.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;

    import
java.util.HashMap; import java.util.Map; @Controller public class HelloController { final String SUCCESS = "success"; @RequestMapping("/success") public String success(Map<String, Object> map){ // classpath:/templates/success.html map.put("hello"
,"你好!"); return SUCCESS; } }

resources/templates/下建立success.html

為了方便使用Thymeleaf標籤,我們引入如下名稱空間

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

html詳細程式碼程式碼如下:

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8" />
        <title>Title</title>
    </head>
    <body>
    Success!
    <p th:text="${hello}"></p>
    </body>
    </html>

測試結果:
這裡寫圖片描述

三、Thymeleaf標籤屬性

序號      特徵              屬性                                  
  1     片段包含        th:insert th:replace                
  2     片段迭代(遍歷)    th:each                             
  3     條件判斷        th:if th:unless th:switch th:case   
  4     宣告變數        th:object th:with                   
  5     一般屬性修改      th:attr th:attrprepend th:attrappend
  6     特定的屬性修改     th:value th:href th:src ...         
  7     文字(標籤主體修改)  th:text th:utext                    
  8     宣告片段        th:fragment                         
  9     移除片段        th:remove                           

四、Thymeleaf表示式語法

首先,我們來看一下Thymeleaf表示式快速總結:

  • 簡單表示式
    • 變量表達式: ${…}(OGNL表示式)
    • 選擇變量表達式: *{…}
    • 訊息表示式: #{…}(獲取國籍化內容)
    • 連結URL表示式: @{…}(定義URL連結)
    • 片段表示式: ~{…}(片段引用)
  • 文字
    • 文字文字:’one text’,’Another one!’,…
    • 號碼文字:0,34,3.0,12.3,…
    • 布林文字:true,false
    • 空文字: 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)
    • 預設: (value) ?: (defaultvalue)
  • 特殊令牌
    • 無操作: _

所有這些功能都可以組合和巢狀:

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

詳細語法,請參照官方!