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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With