胸腺,片段和默认参数 [英] Thymeleaf, fragments and default parameters

查看:214
本文介绍了胸腺,片段和默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了fragments.html文件.它包含以下片段:

I have created fragments.html file. It contains the following fragment:

<div th:fragment="my_fragment(content)">
    <p th:text="${content}"></p>
</div>

我将上面的片段放入了我的视图文件中:

I put the above fragment into my view file:

<div th:replace="fragments :: my_fragment('test')"></div>

现在,我想将两个参数传递给my_fragment,但是我必须确保向后兼容.

Now, I want to pass two parameters to my_fragment, but I must ensure backward compatibility.

我试图解决以下问题:

<div th:fragment="my_fragment(content, defaultParameter='default value')">
    <p th:text="${content}"></p>
</div>

不幸的是,以上解决方案产生了错误:

Unfortunelly, the above solution generated error:

org.springframework.web.util.NestedServletException:请求 处理失败;嵌套的异常是 org.thymeleaf.exceptions.TemplateProcessingException:无法解析 分段.签名"my_fragment(content,defaultParameter ='默认值')" 声明2个参数,但是片段选择​​指定1个参数. 片段选择不正确.

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允许片段签名,而无需使用如下明确参数:

Thymeleaf allows a signature of a fragment without explicit parameters like this:

<div th:fragment="my_fragment">
    <p th:text="${content}"></p>
    <p th:text="${defaultParameter}"></p>
</div>

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

To call this fragment and pass content and defaultParameter you may call the fragment as follows:

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

但是以下方法不起作用:

But the below will not work:

<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. 

因此,如果要保持向后兼容性,应在调用片段时使用命名参数,并且不要在片段签名中指定参数.

So in case you want to maintain backward compatibility, you should use named parameters while calling a fragment and do not specify parameters in a signature of a fragment.

这篇关于胸腺,片段和默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆