gpt4 book ai didi

spring-boot - 第:replace doesn't work well with th:with in Thymeleaf

转载 作者:行者123 更新时间:2023-12-02 21:50:11 24 4
gpt4 key购买 nike

根据Thymeleaf docs

Fragments can include any th:* attributes. These attributes will be evaluated once the fragment is included into the target template (the one with the th:insert/th:replace attribute), and they will be able to reference any context variables defined in this target template.

我的片段

<div th:fragment="link">
<a th:href="@{${url}}"><span th:inline="text">[[${text}]]</span></a>
</div>

这就是我添加它的方式。

<div th:replace="fragments/common :: link" th:with="url='www.google.com', text='Click Me'"></div>

我得到的html

<a href="">
<span>null</span>
</a>

但是,与 th:include 一样可以正常工作,并给出以下 HTML。

<a href="www.google.com">
<span>Click Me</span>
</a>

为什么th:replace工作而th:inlcude工作正常?

注意: th:insert 超出范围,因为我使用的是 Thymeleaf v2.1.5

最佳答案

原因是 th:replace 实际上删除了当前标签,因此您丢失了其中的每个属性,但从片段中获取了所有属性。在您的情况下,这意味着您从未在范围内定义任何 th:with 变量。th:include 的工作方式相反。您失去了片段标签,但保留了布局中定义的所有内容。

考虑这个片段:

<fragmenttag th:fragment="link" style="background-color: red">...</fragmenttag>

和布局:

<layouttag th:include="fragments/common :: link" style="font-size: 250%;"/>
<layouttag th:replace="fragments/common :: link" style="font-size: 250%;"/>

结果是:

<layouttag style="font-size: 250%;">Some Text</layouttag>
<fragmenttag style="background-color: red">Some Text</fragmenttag>

如果你想使用th:replace,因为fragment中有一些重要的属性,你可以在布局中的某些父标签中定义你需要的一切。

<body th:with="url='www.google.com', text='Click Me'">
<div th:replace="fragments/common :: link" ></div>
</body>
<小时/>

您在帖子中引用了文档:

Fragments can include any th:* attributes. These attributes will be evaluated once the fragment is included into the target template (the one with the th:insert/th:replace attribute), and they will be able to reference any context variables defined in this target template.

我在这里没有看到任何矛盾,因为文档的这一部分是关于 th:* 属性在片段内

Fragments (th:fragment part) can include any th:* attributes.

在您的问题中,您正在讨论丢失目标模板中定义的 th:* 属性。但无论如何,这部分是相当困难的,你首先执行包含逻辑

These attributes will be evaluated once the fragment is included

这里没有任何内容可以让您假设您将获得在目标模板或片段主标记中定义的所有内容,因为它们都可以根据您要使用的女巫包含策略进行替换(th:insert/th:替换)。

因此,您定义了 th:with="url='www.google.com', text='Click Me'" 属性,但它从未包含在最终结果模板中,因为您选择了th:replace 包含策略,因此 th:with 属性从未被评估,并且范围内没有 urltext 变量。这里没有矛盾。

关于spring-boot - 第:replace doesn't work well with th:with in Thymeleaf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47032018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com