java - Thymeleaf,片段和默认参数

标签 java spring spring-mvc thymeleaf

我已经创建了 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>

要调用此片段并传递 contentdefaultParameter 您可以按如下方式调用该片段:

<!-- 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/

相关文章:

java - Initialization On Demand Holder 成语

java - 使用十六进制值设置 Android 图像

java - JSON 对象和 Spring @RequestParam

java - 即使使用关键字 "after",AOP 方面也会在给定方法之前执行?

java - 强制 Hibernate 在删除并重新创建数据库后创建表

java - 运行项目时项目中未检测到jsp

java - Spring SimpleFormController - 浏览器后退按钮不起作用

java - 在运行时编译 JUnit 测试 : "No runnable methods"

java - 让程序等待直到单击按钮

java - 为什么 Jackson 会搞乱 application/javascript 的解析?