如何在groovy中使用NodeBuilder模式动态设置节点属性

时间:2011-08-26 12:56:12

标签: groovy markup builder

在使用NodeBuilder模式时,如何根据groovy中的条件设置动态节点属性?

如下所示

def b = DOMBuilder.newInstance()
b.div ( attribute: "value") {
    if (condition) {
        // Set div.dynamicAttribute to true here
    }

}

最好引用条件语句中的当前元素,因为条件可能出现在结构的深处。

1 个答案:

答案 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) {
    ...
}