Reputation: 10628
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.newInstance()
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.
Upvotes: 0
Views: 1535
Reputation: 66059
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) {
...
}
Upvotes: 3