【问题标题】:Trying to ignore unused layout fragment in Thymeleaf Layout Dialect试图忽略 Thymeleaf 布局方言中未使用的布局片段
【发布时间】:2016-04-29 13:43:38
【问题描述】:

有谁知道如果调用页面中没有指定 layout:fragment 是否可以隐藏它?

例如,我有一个页面 layout.html,其中包含类似的内容(其中有一个单独的 fragment.html 文件,其中包含页眉和页脚片段):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      th:lang = "en">
<head>
  <title layout:title-pattern="$CONTENT_TITLE">TITLE</title>
</head>
<body>
  <header layout:replace="fragment :: header">HEADER</header>
  <section layout:fragment="messages">MESSAGES</section>
  <section layout:fragment="content">CONTENT</section>
  <footer layout:replace="fragment :: footer">FOOTER</footer>
</body>
</html>

如果在调用页面的布局中我不想包含“消息”片段,有没有办法通过不包含该代码来做到这一点?例如(比如 simple.html):

<html layout:decorator="layout">
<head>
  <title th:text=#{PAGETITLE_SIMPLE}>SIMPLE PAGE TITLE</title>
</head>
<body>
  <section layout:fragment="content">
    <p>Put in some random content for the body of the simple page</p>
  </section>
</body>

这仍然会将文本“MESSAGES”放入呈现的 HTML 中的

-tag 中。

我已经能够把这个simple.html放进去

<section layout:fragment="messages" th:remove="all"></section>

但这似乎有些草率,并且想知道是否有办法通过将逻辑放入布局中以完全忽略该片段来向布局的用户隐藏它。

使用 Spring 4.1.6、Thymleaf 2.1.4 和 Layout Dialect 1.3.3。

谢谢

【问题讨论】:

    标签: spring-mvc thymeleaf


    【解决方案1】:

    我能够通过将 Serge Ballesta 在 How to check Thymeleaf fragment is defined 中发布的方法应用于布局方言来解决此问题。

    这是重写后的 layout.html 的样子:

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:th="http://www.thymeleaf.org"
          xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
          th:lang = "en">
    <head>
      <title layout:title-pattern="$CONTENT_TITLE">TITLE</title>
    </head>
    <body>
      <header layout:replace="fragment :: header">HEADER</header>
      <section layout:replace="this :: messages">MESSAGES</section>
      <section layout:fragment="content">CONTENT</section>
      <footer layout:replace="fragment :: footer">FOOTER</footer>
    </body>
    </html>
    

    这样,如果调用页面 (simple.html) 只有 content

    ,则不会为消息部分呈现 HTML。但如果页面确实有以下内容,它将按预期包含:

    <section layout:fragment="messages">
      <p>Message 1</p>
      <p>Message 2</p>
    </section>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多