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) {
...
}
精彩评论