1. 程式人生 > 實用技巧 >thymeleaf中th:insert、th:replace、th:include的區別

thymeleaf中th:insert、th:replace、th:include的區別

關於thymeleaf中th:insert、th:replace、th:include的區別

1. th:insert:保留自己的主標籤,保留th:fragment的主標籤

 1 需要替換的片段內容:
 2 <footer th:fragment="copy">
 3    <script type="text/javascript" th:src="@{/plugins/jquery/jquery-3.0.2.js}"></script>
 4 </footer>
 5 
 6 匯入片段:
 7   <div th:insert="footer :: copy"
></div> 8 9 10 結果為: 11 <div> 12 <footer> 13 <script type="text/javascript" th:src="@{/plugins/jquery/jquery-3.0.2.js}"></script> 14 </footer> 15 </div>

2. th:replace:不保留自己的主標籤,保留th:fragment的主標籤

 1 需要替換的片段內容:
 2 <footer th:fragment="copy">
3 <script type="text/javascript" th:src="@{/plugins/jquery/jquery-3.0.2.js}"></script> 4 </footer> 5 6 匯入片段: 7 <div th:replace="footer :: copy"></div> 8 9 結果為: 10 <footer> 11 <script type="text/javascript" th:src="@{/plugins/jquery/jquery-3.0.2.js}"></script
> 12 </footer>

3. th:include:保留自己的主標籤,不保留th:fragment的主標籤(官方3.0不推薦)

 1 需要替換的片段內容:
 2 <footer th:fragment="copy">
 3    <script type="text/javascript" th:src="@{/plugins/jquery/jquery-3.0.2.js}"></script>
 4 </footer>
 5  
 6 匯入片段:
 7   <div th:include="footer :: copy"></div>
 8   
 9 結果為:
10 <div>
11   <script type="text/javascript" th:src="@{/plugins/jquery/jquery-3.0.2.js}"></script>
12 </div>