MUEAS項目,web前端采用thymeleaf作為展示層。這個view解析器,個人覺得非常不錯。簡單而且性能也比較好!個人覺得比JSP和freemarker之類,簡單易用!
今天簡單記錄一下fragment的使用,這個類是JSP的tag,但是確非常簡單。直接在html文件中,將自己覺得可能在多個地方出現的元素塊用fragment包起來!
例如:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 ... 5 </head> 6 <body> 7 <div th:fragment="footer"> 8 © 2013 Footer 9 </div> 10 </body> 11 </html>
在使用的地方,再用include標簽將其引入即可!
例如:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <!--/* Each token will be replaced by their respective titles in the resulting page. */--> 5 <title layout:title-pattern="$DECORATOR_TITLE - $CONTENT_TITLE">Task List</title> 6 ... 7 </head> 8 <body> 9 <!--/* Standard layout can be mixed with Layout Dialect */--> 10 <div th:replace="fragments/header :: header"> 11 ... 12 </div> 13 <div class="container"> 14 <div layout:fragment="content"> 15 <!-- ============================================================================ --> 16 <!-- This content is only used for static prototyping purposes (natural templates)--> 17 <!-- and is therefore entirely optional, as this markup fragment will be included --> 18 <!-- from "fragments/header.html" at runtime. --> 19 <!-- ============================================================================ --> 20 <h1>Static content for prototyping purposes only</h1> 21 <p> 22 Lorem ipsum dolor sit amet, consectetur adipiscing elit. 23 Praesent scelerisque neque neque, ac elementum quam dignissim interdum. 24 Phasellus et placerat elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. 25 Praesent scelerisque neque neque, ac elementum quam dignissim interdum. 26 Phasellus et placerat elit. 27 </p> 28 </div> 29 <div th:replace="fragments/footer :: footer">© 2014 The Static Templates</div> 30 </div> 31 </body> 32 </html>
注意:th:fragment定義的片段,在需要的地方,可以用th:include或者th:replace進行帶入!
還有,所有的fragment可以寫在一個文件里面,也可以單獨存在。可以是一個html文件中的一部分。只要你需要,帶上th:fragment的標簽進行定義,讓其為一個fragment即可。有點需要注意的是,片段所在的文件的路徑,要用“/”分開路徑,根路徑為templates所在的路徑。
比如:
1 <body> 2 <div class="container"> 3 <div th:include="exam/special/geeker/geeker::geeker-base-header"></div> 4 <div class="geeker-content"> 5 <div th:include="exam/special/geeker/geeker::geeker-base-left"></div> 6 <div class="geeker-main"> 7 </div> 8 <div class="geeker-right"> 9 </div> 10 </div> 11 </div> 12 </body>
是不是很簡單易用?我覺得很不錯!