4

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.

3 Answers 3

6

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That did the trick. I also found another way, and a way for a multidimensional array so I'll use that as the answer.
Glad I could help! :)
3

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.