select context variables properties based on other variables in thymeleaf (dynamically)

五迷三道 提交于 2019-12-24 04:17:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!