java使用“this::content”或“::content”不按预期工作,包含来自同一thymeleaf模板的片段
我包含了来自同一模板文件的模板片段。文件第“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"
对我来说才有效
这是示例代码:
家庭控制器。java
@Controller
class HomeController {
@RequestMapping({ "/", "index", "home" })
String index(Model model) {
return "test";
}
}
测试。html
<!DOCTYPE html>
<html>
<head></head>
<body>
<ul th:replace="test-fragment :: contentA" />
</body>
</html>
测试片段。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 Boot1.3.2进行测试。释放
编辑:
我做了一个小的测试项目来重现这个问题,可以在这里找到:https://github.com/t-cst/thymeleaf-springboot-test
编辑:
经过一些调试后,我发现当片段选择器为"this :: contentB"
或" :: contentB"
时,模板名称解析为test
而不是test-framgent
。这项工作在以下地点完成:
来自thymeleaf-2.1.4的{
/* 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
# 1 楼答案
如果有人在这里以相同的问题结束,这在
thymeleaf 2.1.4.RELEASE
版本中是不可能的,但它将在下一版本3.0
在这个issue comment可以找到一个全面的解释