根据 thymeleaf 中的其他变量选择上下文变量属性(动态) [英] select context variables properties based on other variables in thymeleaf (dynamically)
问题描述
我是使用 Thymeleaf 的初学者.我有一个设置为上下文变量的对象.ctx.setVariable("name", myObject);
I am a beginner in using Thymeleaf. I have an object which is set as a context variable.
ctx.setVariable("name", myObject);
这个对象有几个属性,但我不能只使用`name.property1.subproperty1'
this object has several properties, but I can't just select them using `name.property1.subproperty1'
因为在某些时候我想在同一个模板中呈现 name.property1.subproperty
和 name.property2.subproperty
,并且我不想对此进行硬编码模板中的选择,因为它可能会改变.
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}
换句话说,我想从java代码中控制要呈现的属性.我有属性模板,我不想为相同类型创建更多模板,因为如果我将属性模板包含到 myObject Template 中,它只会被渲染一次,这就是我选择这种方法的原因.
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.
推荐答案
使用以下语法(请参阅:4.12 预处理):
Use the following syntax (see: 4.12 Preprocessing):
${myObject.?__${listOfProperties[0]}__.subproperty1} ${myObject.?__${listOfProperties[1]}__.subproperty2}
这篇关于根据 thymeleaf 中的其他变量选择上下文变量属性(动态)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!