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



我有一个通用布局,默认情况下,它应该在每个页面上显示一个(基本)搜索表单,除了搜索页面本身,它已经包含了一个(更高级)搜索表单。

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

下面是我想做的一个例子:

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>

是的,这是完全可能的,尽管Thymelaf的文档没有明确说明

您所要做的就是使用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>

标题片段-片段/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中使用了它。不需要将它从decorator传递到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>

是的,可以传递参数,但需要使用layout:include而不是layout:decoratorlayout:fragment

类似于Thymelaf的th:include,但允许整个元素片段添加到包含的页面。如果你有一些HTML,这很有用您想要重用,但其内容过于复杂而无法重用单独使用上下文变量来确定或构造。

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

你应该看看这个文档,它会给你详细的使用方法

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

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

最新更新