我是使用Thymeleaf的初学者。我有一个被设置为上下文变量的对象。
ctx.setVariable("name", myObject);
这个对象有几个属性,但我不能只选择它们 `name.property1.subproperty1'
因为在某些时候我想在同一模板中呈现name.property1.subproperty
和name.property2.subproperty
,我不想在模板中对此选择进行硬编码,因为它可能会发生变化。
我想要声明另一个上下文变量,如:
String[] listOfProperties = {"property1", "property2"};
ctx.setVariable("properties", listOfProperties);
并在模板中执行类似的操作:
${myObject.?[listOfProperties[0]].subproperty1}
${myObject.?[listOfProperties[1]].subproperty2}
换句话说,我想从java代码控制要渲染的属性。 我有属性模板,我不想为同一类型创建更多模板,因为如果我将属性模板包含在myObject模板中,它将只渲染一次,这就是我选择这种方法的原因。
对不起,我不知道要解释得更好...... 感谢。
答案 0 :(得分:3)
使用以下语法(请参阅:4.12 Preprocessing):
${myObject.?__${listOfProperties[0]}__.subproperty1} ${myObject.?__${listOfProperties[1]}__.subproperty2}