Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array as argument in Thymeleaf fragment

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.

like image 896
BigJ Avatar asked Oct 29 '25 10:10

BigJ


2 Answers

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>
like image 74
Alain Cruz Avatar answered Oct 31 '25 11:10

Alain Cruz


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.

like image 39
BigJ Avatar answered Oct 31 '25 10:10

BigJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!