2016-06-01 38 views
2

我希望能够使用thymeleaf片段,使用其中的所有内容,但有时会从使用该片段的页面添加额外内容。典型案例:我有一个脚本模板,其中包含我想要在每个页面上使用的脚本引用。在一些页面上,我想添加另一个脚本引用,但不是全部。如何“添加”到Thymeleaf片段,而不是替换

我有以下设置(降低复杂度的集中的点)在我的web应用程序:

的layout.html:

<html> 
    <body> 
     <div class="container"> 
      <div fragment="content"></div> 
     </div> 
     <div th:replace="shared/footer :: footer"></div> 
    </body> 
</html> 

共享/ footer.html

<html> 
    <body> 
     <div th:fragment="footer" th:remove="tag"> 
      <script th:src="{@/scripts/a.js}"></script> 
     </div> 
    </body> 
</html> 

index.html

<html> 
    <body> 
     <div th:fragment="content" class="myClass"> 
      <h1>Oh hello</h1> 
     </div> 

     <!-- what do i put here?!!! --> 
    </body> 
</html> 

我想什么做的是能够一些额外的内容添加到页脚,在index.html:

如:

<div th:addExtraStuff="footer"> 
    <script th:ref="@{scripts/b.js"></script> 
</div> 

所以最后的结果是这样的:

<html> 
     <body> 
      <div class="container"> 
       <div class="myClass"> 
        <h1>Oh hello</h1> 
       </div> 
      </div> 
      <div> 
       <script src="/scripts/a.js"></script> 
       <script src="/scripts/b.js"></script> 
      </div> 
     </body> 
    </html> 

显然th:addExtraStuff不存在 - 但你明白了。我想要现有的内容,并能够提供我自己的内容。我认为如果我将所有可能性都放在片段中,然后使用评估来决定是否真的包含这种可能性,那么它会变得过于复杂。但我可能是错的。

回答

1

我已经解决了这个问题,不使用自定义方言的一种方法是在我用作布局模板的片段上使用参数,我称之为“主布局”。这个例子允许你省略你不需要覆盖的元素,但是你提供的任何东西都会被添加到'main-layout'片段中的任何元素中。

的基本模板看起来像这样

主view.html

<!DOCTYPE html> 
    <html lang="en" xmlns:th="http://www.thymeleaf.org" th:fragment="main-layout"> 
    <head> 
     <title>Template Head Title</title> 
     <th:block th:replace="${head} ?: ~{}" /> 
    </head> 
    <body> 
     <header> 
      Common Template Header Here 
      <th:block th:replace="${contentHeader} ?: ~{}" /> 
     </header> 
     <main> 
      Common Template Content Here 
      <th:block th:replace="${content} ?: ~{}" /> 
     </main> 
    </body> 
    <footer> 
     Common Template Footer Here 
     <th:block th:replace="${footer} ?: ~{}" /> 
    </footer> 
</html> 

,并用它看起来像

<!DOCTYPE HTML> 
<html th:replace="main-view.html :: main-layout (head=~{:: head}, contentHeader=~{:: header}, content=~{:: main}, footer=~{:: footer})"> 
    <head th:remove="tag"> 
     <title>Greeting Head</title> 
    </head> 
    <body> 
     <header th:remove="tag"> 
      Greeting Content Header 
     </header> 
     <main th:remove="tag"> 
      Greeting Content 
     </main> 
    </body> 
    <footer th:remove="tag"> 
     Greeting Footer 
    </footer> 
</html> 
-3

一种方法我已经解决了这个,无需使用自定义方言,就是在我用作布局模板的片段上使用参数,我称之为“主布局”。这个例子允许你省略你不需要覆盖的元素,但是你提供的任何东西都会被添加到'main-layout'片段中的任何元素中。

+1

由于先前答案的无耻复制粘贴而导致投票减少。 –

相关问题