1. 程式人生 > 其它 >18.檢視解析和模板引擎

18.檢視解析和模板引擎

1.thymeleaf

基本語法:
    1.變數取值:${...} 獲取請求域,session域,物件等的值
    2.選擇變數:*{...}獲取上下文物件值
    3.訊息:#{...}獲取國際化等值
    4.連線:@{...}生成連結
    5.片段表示式:~{...}jsp:include作用,引入公共頁面
    
基本使用:

1.引入thymeleaf的jar包
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    

2.thymeleaf的自動配置類如下
    @Configuration(
        proxyBeanMethods = false
    )
    @EnableConfigurationProperties({ThymeleafProperties.class})
    @ConditionalOnClass({TemplateMode.class, SpringTemplateEngine.class})
    @AutoConfigureAfter({WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class})
    public class ThymeleafAutoConfiguration {
        
    }
    
3.總結:
    1.所有thymeleaf的配置等值都是在ThymeleafProperties類中
    2.配置好了SpringTemplateEngine
    3.配置好了ThymeleafViewResolver
    4.並且制定了開發的前後綴:
        public class ThymeleafProperties {
            private static final Charset DEFAULT_ENCODING;
            public static final String DEFAULT_PREFIX = "classpath:/templates/";
            public static final String DEFAULT_SUFFIX = ".html";
            ...
        }
        
樣例:
1.resource/templates資料夾下建立success.html頁面
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        你好!thymeleaf
    </body>
    </html>

2.控制類測試:
    @Controller
    public class ThymealfController {
        @GetMapping("/hello")
        public String getThymealf(){
            //只需要寫頁面名稱,會自動去resource/templates路徑下找success.html
            return "success";
        }
    }
Thymealf的抽取公共頁,並引入!
場景:因為很多html頁面的格式一樣,例如後臺管理系統,每個頁面的左側導航欄和頭都是一樣的,故將相同的程式碼抽取到同一個頁面,例如comm.html,再在其他頁面去引入comm.html的具體程式碼
具體引入有三種方式:
例如:comm.html頁面中有以下程式碼:th:fragment=""去標註公共頁的程式碼段,這個值必須唯一!
    <footer th:fragment="copy">
      &copy; 2011 The Good Thymes Virtual Grocery
    </footer>
    
1.th:insert:將引入程式碼插入標籤中
    例如:
        <body>
          <div th:insert="comm:: copy"></div>
       </body>
   結果為:
   <body>
        <div>
            <footer>
              &copy; 2011 The Good Thymes Virtual Grocery
            </footer>
          </div>     
    </body>
    
2.th:replace:直接將整個標籤替換為引入程式碼
    例如:
        <div th:replace="comm :: copy"></div>
    結果:
        <footer>
            &copy; 2011 The Good Thymes Virtual Grocery
          </footer>

3.th:include:
    例如:將引入程式碼的內容,不包括標籤,插入!
        <div th:include="footer :: copy"></div>
    結果:
        <div>
            &copy; 2011 The Good Thymes Virtual Grocery
          </div>