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

时间:2015-02-20 18:55:09

标签: thymeleaf

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

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

以下是我想要做的一个例子:

的layout.html

<html layout:???="displayShowForm = true">
    ...
    <form action="search" th:if="${displayShowForm}">...</form>
    ...
    <div layout:fragment="content">...</div>

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

<html layout:decorator="layout">
    ...
    <div layout:fragment="content">...</div>

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

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

2 个答案:

答案 0 :(得分: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>

标题片段 - fragments / 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>

主页文件 - 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>

在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>

答案 1 :(得分:1)

是的,可以传递参数,但您需要使用layout:include代替layout:decoratorlayout:fragment

  

与Thymeleaf的th:include类似,但允许整个传递   元素片段到包含的页面。如果你有一些HTML,这很有用   你想重用,但其内容太复杂了   单独确定或构建上下文变量。

来源:https://github.com/ultraq/thymeleaf-layout-dialect

您应该查看this documentation,它会为您提供有关使用方法的详细信息。

在您的情况下,它可能看起来像:

<div layout:include="form" th:with="displayShowForm=true"></div>

form的布局页面中:

<div layout:fragment="form">
    <div th:if="${displayShowForm} == true">
        <form action="basicSearch"></form>
    </div>
    <div th:if="${displayShowForm} == false">
        <form action="advancedSearch"></form>
    </div>
</div>