Passing multiple variables to a fragment

classic Classic list List threaded Threaded
4 messages Options
Reply | Threaded
Open this post in threaded view
|

Passing multiple variables to a fragment

Parminder
I understand that I can pass a variable to a fragment by using the "th:with" tag like so:

<div th:include="path/fragments :: fragment1" th:with="myVar=(${myObj})" />

and then I can use the myVar in the fragment with ${myVar} syntax. But how do I pass more than 1 variables to the fragment? Only one th:with attribute is allowed per element and I do not know the syntax to send more than 1 variables in the same th:with attribute. The th:href attribute allows multiple parameters like (param1=xxx, param2=yyy) but that doesn't seem to be the case with th:with.
Reply | Threaded
Open this post in threaded view
|

Re: Passing multiple variables to a fragment

Emanuel
Administrator
You should be able to just comma-separate the variables.  An example in the Local Variables section of the Using Thymeleaf docs has this example:

<div th:with="firstPer=${persons[0]},secondPer=${persons[1]}">
Reply | Threaded
Open this post in threaded view
|

Re: Passing multiple variables to a fragment

Parminder
Aah thank you so much! I missed that documentation it seems.
Reply | Threaded
Open this post in threaded view
|

Re: Passing multiple variables to a fragment

jjbenson
In reply to this post by Parminder
Hi Parminder,

  I tried this using ognl, with a comma separated variable list and an enclosed template fragment, it seems to work just fine:

<div th:with="myVar=${myObj},myOtherVar=${myOtherObj}">
  <div th:include="path/fragments :: fragment1" />
</div>

  If also seems to work with an inline th:with

  <div th:include="path/fragments :: fragment1" th:with="myVar=${myObj},myOtherVar=${myOtherObj}" />

  What's more, you can even combine the 2 forms:

<div th:with="myVar=${myObj},myOtherVar=${myOtherObj}">
  <div th:include="path/fragments :: fragment1" th:with="myVar2=${myObj2},myOtherVar2=${myOtherObj2}"/>
</div>

  Note: I only tried simple cases and only ognl, not Spel.

  Cheers,

   JJB