thymeleaf optional fragment parameter

Solutions on MaxInterview for thymeleaf optional fragment parameter by the best coders in the world

showing results for - "thymeleaf optional fragment parameter"
Roberta
25 Jun 2016
1
2
3The best way to allow optional parameter for a fragment is to declare them with "th:with" and describe them with meaningful default values.
4
5So, you define explicit your mandatory and your optional values in the declaration tag of your fragment.
6
7Here is simple example, with 1 mandatory and 2 optional parameters:
8
9<div th:fragment="printGreetings (name)" th:with="title=${title} ?: 'Mr.', greeting=${greeting} ?: 'Hello'">
10    <span th:text="${greeting}">Hello</span>
11    <span th:text="${title}">Mr.</span>
12    <span th:text="${name}">John Doe</span>
13</div>
14
15You can then call it like the following:
16
17<div th:replace="fragments :: printGreetings (name='daniel')">
18   Hello Mr. Daniel
19</div>
20<div th:replace="fragments :: printGreetings (name='Lea', title='Ms.')>
21   Hello Ms. Lea
22</div>
23<div th:replace="fragments :: printGreetings (name='Lea', title='Ms.', greeting='Hi')>
24   Hi Ms. Lea
25</div>
26
27(Please note that all values inside the tags are replaced by the dynamic ones. It's just for better reading.)
28