Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

java - Thymeleaf, fragments and default parameters

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>

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

I tried to solve the problem as follows:

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

Any idea?

question from:https://stackoverflow.com/questions/22093149/thymeleaf-fragments-and-default-parameters

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

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>

And the message is self-explonatory:

 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...