th:insert、th:replace、th:include抽取和引用頁面公共片段、傳參等


一、抽取公共片段

  • th:fragment  給片段命名

將公共片段抽取出來,並在頂級標簽內使用th:fragment給該片段命名。

例如:將公共片段抽取出來放到comment/bar.html中:

     

<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar">   <a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Company name</a>   <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">   <ul class="navbar-nav px-3">
    <li class="nav-item text-nowrap">
      <a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Sign out</a>
    </li>
  </ul>
</nav>

這樣我們就抽取了一個名叫topbar的公共片段。

 

二、引入公共片段

1.三種引入片段的方式:

  • th:insert :將公共片段插入到聲明引入的標簽中
  • th:replace:將公共片段替換掉聲明引入的標簽
  • th:include:將公共片段中的內容包含進聲明引入的標簽內。

這三中引入的效果如下:

公共片段:
<footer th:fragment="copy">
&copy; 2011 The Good Thymes Virtual Grocery
</footer>

th:insert :

<div th:insert="footer :: copy"></div>

效果:
<div>
<footer>
&copy; 2011 The Good Thymes Virtual Grocery
</footer>
</div>

th:replace:

<div th:replace="footer :: copy"></div>
效果:
<footer>
&copy; 2011 The Good Thymes Virtual Grocery
</footer>

th:include:

<div th:include="footer :: copy"></div>
效果:
<div>
&copy; 2011 The Good Thymes Virtual Grocery
</div>

2.引入片段的表達式

在上邊例子中我們可能有疑問 footer :: copy 這是什么意思?

其實這是一種引入片段的表達式之一,下面我們講兩種引入片段的表達式。

(1) 通過片段名引入片段的表達式: ~{模板名::片段名}

  如我們需要引入上邊第一部分演示的片段,我們需要這樣寫

<div th:replace="~{commons/bar::topbar}"></div>

注意 ~{}可以省略,開發中常常不會寫~{}的方式來引入,而是通過下邊這種,更加簡潔。但是如果是行內寫法,則必須加上~{},例如  [[~{}]]  或  [(~{  })]

<div th:replace="commons/bar::topbar"></div>

 

(2)通過選擇器引入片段的表達式:~{模板名::選擇器}

例如引入id為user的片段:

<div th:replace="commons/bar::#user"></div>

#號為id選擇器

 

三、引用片段並傳參

1.傳遞參數

只需要在表達式后邊跟個小括號即可傳遞參數,小括號內通過鍵值對的方式設置值(key=value)

<div th:replace="commons/bar::topbar(username='zhangsan')"></div>

 2.獲取參數

 在目標頁面(引用片段表達式中模板名對應的頁面)通過變量表達式${} 獲取值即可。

 

<h4 th:text="${username}"></h4>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM