问题
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.
回答1:
Use the following syntax (see: 4.12 Preprocessing):
${myObject.?__${listOfProperties[0]}__.subproperty1} ${myObject.?__${listOfProperties[1]}__.subproperty2}
来源:https://stackoverflow.com/questions/19784592/select-context-variables-properties-based-on-other-variables-in-thymeleaf-dynam