我已经创建了 Fragments.html 文件。它包含以下片段:
<div th:fragment="my_fragment(content)">
<p th:text="${content}"></p>
</div>
我把上面的片段放到我的 View 文件中:
<div th:replace="fragments :: my_fragment('test')"></div>
现在,我想将两个参数传递给 my_fragment,但我必须确保向后兼容。
我尝试如下解决问题:
<div th:fragment="my_fragment(content, defaultParameter='default value')">
<p th:text="${content}"></p>
</div>
不幸的是,上面的解决方案产生了错误:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Cannot resolve fragment. Signature "my_fragment (content,defaultParameter='default value')" declares 2 parameters, but fragment selection specifies 1 parameters. Fragment selection does not correctly match.
有什么想法吗?
最佳答案
Thymeleaf 允许在没有显式参数的情况下对片段进行签名,如下所示:
<div th:fragment="my_fragment">
<p th:text="${content}"></p>
<p th:text="${defaultParameter}"></p>
</div>
要调用此片段并传递 content
和 defaultParameter
您可以按如下方式调用该片段:
<!-- both parameters not specified -->
<div th:replace="fragments :: my_fragment"></div>
<!-- only content parameter specified -->
<div th:replace="fragments :: my_fragment(content='a')"></div>
<!-- both parameters specified -->
<div th:replace="fragments :: my_fragment(content='a', defaultParameter='b')"></div>
但下面的行不通:
<div th:replace="fragments :: my_fragment('a', 'b')"></div>
而且消息是不言自明的:
Signature "my_fragment" declares no parameters, but fragment selection did specify parameters in a synthetic manner (without names), which is not correct due to the fact parameters cannot be assigned names unless signature specifies these names.
所以如果你想保持向后兼容性,你应该在调用片段时使用命名参数,并且不要在片段的签名中指定参数。
关于java - Thymeleaf,片段和默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22093149/