Question

I am a beginner in using Thymeleaf. I have an object which is set as a context variable. ctx.setVariable("name", myObject);

this object has several properties, but I can't just select them using `name.property1.subproperty1'

because at some point I want to render name.property1.subproperty and name.property2.subproperty in the same template, and I don't want to hardcode this selection in the template because it might change.

I was thinking to declare another context variable like:

String[] listOfProperties = {"property1", "property2"}; ctx.setVariable("properties", listOfProperties);

and do something like that in the template:

${myObject.?[listOfProperties[0]].subproperty1} ${myObject.?[listOfProperties[1]].subproperty2}

In other words, I want to control from java code what property to be renderd. I have templates for properties and I don't want to create more templates for the same type, because if I include the property template into myObject Template it is going to be rendered only once, that is why I chose this approach.

I am sorry I don't know to explain better... Thanks.

Was it helpful?

Solution

Use the following syntax (see: 4.12 Preprocessing):

${myObject.?__${listOfProperties[0]}__.subproperty1} ${myObject.?__${listOfProperties[1]}__.subproperty2}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top