是否可以将参数传递给百里香布局 - 方言中的布局?

Xav*_*ury 5 thymeleaf

我有一个共同的布局,默认情况下,应该在每个页面上显示(基本)搜索表单,但搜索页面本身除外,其中包含(更高级)搜索表单.

是否可以将参数从我的搜索页面传递到布局,以便不显示默认搜索表单?

这是我想做的一个例子:

的layout.html

<html layout:???="displayShowForm = true">
    ...
    <form action="search" th:if="${displayShowForm}">...</form>
    ...
    <div layout:fragment="content">...</div>
Run Code Online (Sandbox Code Playgroud)

home.html(显示默认搜索表单)

<html layout:decorator="layout">
    ...
    <div layout:fragment="content">...</div>
Run Code Online (Sandbox Code Playgroud)

search.html(隐藏默认搜索表单)

<html layout:decorator="layout (displayShowForm = false)">
    ...
    <div layout:fragment="content">
        ...
        <form action="advancedSearch">...</form>
Run Code Online (Sandbox Code Playgroud)

小智 14

是的,尽管Thymeleaf的文档没有明确说明,但它完全有可能.

您所要做的就是使用th:with属性传递您的参数.可能还有其他方法,但这似乎是最直接的方法.

这是我的实现的精简版:

默认装饰器 - fragments/layout/default.html

<!doctype html>
<html xmlns:layout="http://www.thymeleaf.org" xmlns:th="http://www.thymeleaf.org">
<body>
  <div th:replace="fragments/header :: main"></div>
  <div layout:fragment="content">
    main content goes here
  </div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

标题片段 - fragment/header.html

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
  <div th:fragment="main">
    <nav>
      <ul>
        <li><a href="#" th:classappend="${currentPage == 'home'} ? 'active'">Home Page</a></li>
        <li><a href="#" th:classappend="${currentPage == 'about'} ? 'active'">About</a></li>
      </ul>
    </nav>
  </div>
</body>
Run Code Online (Sandbox Code Playgroud)

主页文件 - home.html

<!doctype html>
<html layout:decorator="layout/default" th:with="currentPage='home'"
  xmlns:layout="http://www.thymeleaf.org/" xmlns:th="http://www.thymeleaf.org">
<body>
  <div layout:fragment="content">
    This is my home page content... thrilling, isn't it?
  </div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

在home.html文件中,您可以看到我包含默认装饰器并使用th:with属性传递我的参数.我实际上并没有在我的布局装饰器中使用我的参数,但我在header.html中使用它,它包含在装饰器中.无需将它从装饰器传递到header.html片段,因为它已经在范围内.

也没有必要对header.html中的currentPage变量进行NULL检查.从home.html中删除参数时,不会附加活动的CSS类.

如果我要渲染home.html,我希望看到以下输出:

<!doctype html>
<html>
<body>
  <nav>
    <ul>
      <li><a href="#" class="active">Home Page</a></li>
      <li><a href="#">About</a></li>
    </ul>
  </nav>
  <div>
    This is my home page content... thrilling, isn't it?
  </div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)