开发者

How to set node attribute dynamically using NodeBuilder pattern in groovy

开发者 https://www.devze.com 2023-03-30 19:36 出处:网络
How do I set a dynamic node attribute based on a condition in groovy when using the NodeBuilder pattern?

How do I set a dynamic node attribute based on a condition in groovy when using the NodeBuilder pattern?

Like the following

def b = DOMBuilder.开发者_如何学CnewInstance()
b.div ( attribute: "value") {
    if (condition) {
        // Set div.dynamicAttribute to true here
    }

}

Preferably it would be nice to reference the current element in the conditional statement since the condition might appear deep down in the structure.


The easiest way to do this is to evaluate the condition for the dynamic attribute outside the node closure. For Example:

if (condition) {
    b.div(attribute: "value", dynamicAttribute: true) {
        ...
    }
} else {
    b.div(attribute: "value") {
        ...
    }
}

Alternatively, you can create a map of the attributes beforehand:

def attributes = [attribute: "value"]
if (condition) {
    attributes['dynamicAttribute'] = true
}
b.div(attributes) {
    ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消