在使用NodeBuilder模式时,如何根据groovy中的条件设置动态节点属性?
如下所示
def b = DOMBuilder.newInstance()
b.div ( attribute: "value") {
if (condition) {
// Set div.dynamicAttribute to true here
}
}
最好引用条件语句中的当前元素,因为条件可能出现在结构的深处。
答案 0 :(得分:3)
最简单的方法是评估节点闭包之外的动态属性的条件。例如:
if (condition) {
b.div(attribute: "value", dynamicAttribute: true) {
...
}
} else {
b.div(attribute: "value") {
...
}
}
或者,您可以事先创建属性的地图:
def attributes = [attribute: "value"]
if (condition) {
attributes['dynamicAttribute'] = true
}
b.div(attributes) {
...
}