Reputation: 2032
Is it possible to pass an array to a fragment like this:
<div th:replace="fragments :: test_fragment( {'one', 'two', 'three'} )"></div>
And iterate in the fragment like this:
<div th:fragment="test_fragment(numberArray)">
<span th:each="number : ${numberArray}" th:text="${number}"></span>
</div>
As a bonus, are multidimensional arrays also possible?
I am using Thymeleaf in a Spring Boot 2.0 project.
Upvotes: 3
Views: 4781
Reputation: 164
Alternate approach to the accepted answer:
<div th:replace="fragments :: test_fragment('one,two,three')"></div>
And iterate as follows:
<div th:fragment="test_fragment(numberArray)">
<span th:each="number : ${#strings.arraySplit(numberArray, ',')}" th:text="${number}"></span>
</div>
Helps to avoid warnings from certain IDEs which complain about the comma (,) occurring within bracketed ${} items.
Upvotes: 0
Reputation: 5097
Yes, it is possible. The following code should do the trick. The only difference, is the added ${}
, outside the array.
<div th:replace="fragments :: test_fragment(${ {'one', 'two', 'three'} })"></div>
Upvotes: 5
Reputation: 2032
I've found two ways: the fragment parameters and th:with.
Fragment parameter array:
<div th:replace="~{fragments :: test_fragment(arrayX = ${ {'a', 'b'} }) }"></div>
Frag parameter array multidimensional:
<div th:replace="~{fragments :: test_fragment(arrayX = ${ {{'a1','a2'},{'b1','b2'}} } ) }"></div>
th:with array:
<div th:insert="~{fragments :: test_fragment}" th:with="arrayX=${ {'a','b'} }"></div>
th:with array multidimensional:
<div th:insert="~{fragments :: test_fragment}" th:with="arrayX=${ {{'a1','a2'},{'b1','b2'}} }"></div>
Notice that I used th:insert when I used th:with. This is because th:replace would replace the div line and thus the th:with, which causes the arrayX to not be available.
Upvotes: 3