【问题标题】:Pass Thymeleaf block content as variable to fragment将 Thymeleaf 块内容作为变量传递给片段
【发布时间】:2020-12-31 01:06:35
【问题描述】:

我正在尝试创建一个片段来表示具有自定义内容的卡片。我想做类似的事情:

<div class="card" th:fragment="myfragment" th:utext="${content}">
</div>

然后用 as

<th:block th:replace="myfragment">
   <p>Some custom content that would be the value of 'content'</p>
</th:block>

这将使处理更大的 html 变得更容易,而在属性中写入会有点难看。 (基本上我正在寻找与 Blade 的视图和插槽类似的功能)

编辑: 我知道片段参数化,但在属性中传递长而复杂的 html 代码非常难看且难以管理。

一个更具描述性的例子是一张卡片,它的卡片主体不是 p,而是一张桌子。

【问题讨论】:

标签: java html spring thymeleaf


【解决方案1】:

Thymeleaf 支持参数化片段。使用方法如下:

片段定义:

_fragments/my_fragments.html:

<th:block th:fragment="myFragment(p1, p2, p3)">
   //do sth with p1, p2, p3
</th:block>

使用它:

<th:block th:replace="_fragments/my_fragments :: myFragment(${p1}, ${p2}, ${p3} )">
</th:block>

参考:

【讨论】:

  • 我知道这一点,如果我的内容是一个带有一些文本的简单 p,它就可以工作,但是在那里扔一个又长又复杂的 html 代码真的很难看。
  • 它也适用于复杂的对象图......不仅仅是字符串。这是一个例子github.com/gtiwari333/spring-boot-web-application-seed/blob/…
  • 但是如何给变量赋值呢?我可以说类似 var = "some HTML code" 之类的话,而不在我的控制器中执行此操作并将 html 作为字符串处理吗?
  • ganeshtiwaridotcomdotnp.blogspot.com/2020/09/… 看到这个。您可以传递来自 Thymeleaf 的常量值或从服务器接收的值。
  • 这与我的问题无关。请参阅下面的答案,了解我想要实现的目标。我完全知道内容可以作为 thymeleaf 变量传递,但是您真的会考虑将复杂的 html 代码放在元素属性中的良好做法吗? (th:with="/*HTML 代码*/")
【解决方案2】:

Soo,也许不是最好的解决方案,但我设法根据这个 Other SO thread 和这个 Example code

我创造了一种新的方言,所以我可以这样说:

<zms:card header="'ASD Title'">
   <div th:text="${first_name}"></div>
   asdasd card works asdasd
</zms:card>

它会渲染这个:

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <div class="d-inline-block">
            <h6 class="m-0 font-weight-bold">ASD Title</h6>
        </div>
    </div>
    <div class="card-body">
        <div>Name</div>
        asdasd card works 
    </div>
</div>

【讨论】:

    猜你喜欢
    • 2012-11-30
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 2019-08-17
    • 2016-03-29
    • 2017-11-28
    相关资源
    最近更新 更多