thymeleaf之fragment

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       &copy; 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">&copy; 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>

是不是很简单易用?我觉得很不错!

原文地址:https://www.cnblogs.com/shihuc/p/5090902.html