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?
The best way to allow optional parameter for a fragment is to declare them with "th:with" and describe them with meaningful default values.
So, you define explicit your mandatory and your optional values in the declaration tag of your fragment.
Here is simple example, with 1 mandatory and 2 optional parameters:
You can then call it like the following:
(Please note that all values inside the tags are replaced by the dynamic ones. It's just for better reading.)
At last I've solved task like this:
But it is overhead:(
Also ask a question to issue Allow fragment parameters to have default values
Thymeleaf allows a signature of a fragment without explicit parameters like this:
To call this fragment and pass
content
anddefaultParameter
you may call the fragment as follows:But the below will not work:
And the message is self-explonatory:
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.
If you want to provide a default value (as in your case) you can use the elvis operator to specify a default value, for example:
see: elvis-operator