gpt4 book ai didi

java - 使用 "this::content"或 "::content"包含来自同一 thymeleaf 模板的片段未按预期工作

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:16:03 24 4
gpt4 key购买 nike

我包括来自同一模板文件的模板片段。文档的“8.1 Including template fragments - Defining and referencing fragments”部分指出:

"::domselector" or "this::domselector" Includes a fragment from the same template.

如果我没理解错的话,我应该可以这样引用片段:th:include="this::contentB" 或者 th:include="::contentB "但只有完整引用 th:include="test-fragment::contentB" 对我有用。

这是示例代码:

HomeController.java

@Controller
class HomeController {
@RequestMapping({ "/", "index", "home" })
String index(Model model) {
return "test";
}
}

test.html

<!DOCTYPE html>
<html>
<head></head>
<body>
<ul th:replace="test-fragment :: contentA" />
</body>
</html>

test-fragment.html

<!DOCTYPE html>
<html>
<head></head>
<body>
<ul th:fragment="contentA">
<li th:each="idx : ${#numbers.sequence(1,4)}" th:switch="${idx}">

<th:block th:case="1"
th:include="test-fragment :: contentB"
th:with="strVar = 'One'"/>

<th:block th:case="2"
th:include="this :: contentB"
th:with="strVar = 'Two'"/>

<th:block th:case="3"
th:include=" :: contentB"
th:with="strVar = 'Three'"/>

<th:block th:case="*"
th:include="/test-fragment :: contentB"
th:with="strVar = 'Other'"/>
</li>
</ul>

<span th:fragment="contentB">
<span th:text="|value: ${strVar}|" />
</span>
</body>
</html>

输出是:

<!DOCTYPE html>
<html>
<head></head>
<body>
<ul>
<li><span>value: One</span></li>
<li></li>
<li></li>
<li><span>value: Other</span></li>
</ul>
</body>
</html>

案例 2 和案例 3 缺失。我究竟做错了什么?

我正在使用 Spring Boot 进行测试1.3.2.发布

编辑:

我做了一个小的测试项目来重现这个问题,它可以在这里找到:https://github.com/t-cst/thymeleaf-springboot-test

编辑:

经过一些调试,我发现当片段选择器是 "this::contentB""::contentB" 时,模板名称被解析为 test 而不是 test-framgent。这是在以下位置完成的:

StandardFragment#extractFragment:189 来自 thymeleaf-2.1.4.RELEASE:

/* 186 */  String targetTemplateName = getTemplateName();
if (targetTemplateName == null) {
if (context != null && context instanceof Arguments) {
targetTemplateName = ((Arguments)context).getTemplateName();
/* 190 */ } else {
throw new TemplateProcessingException(
"In order to extract fragment from current template (templateName == null), processing context " +
"must be a non-null instance of the Arguments class (but is: " +
(context == null? null : context.getClass().getName()) + ")");
/* 195 */ }
}

但我仍然不知道为什么在我的测试中会出现这种情况。

编辑:

我也曾在 thymeleaf forum 询问过.也许这是一个错误。我打开了一个issue .

最佳答案

如果有人遇到同样的问题,这在 thymeleaf 2.1.4.RELEASE 版本中是不可能的,但它会在下一个版本 3.0

可以在这个 issue comment 找到全面的解释.

关于java - 使用 "this::content"或 "::content"包含来自同一 thymeleaf 模板的片段未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35322784/

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