Reputation: 3007
I am trying to create a multi line string in Groovy. I have a list of strings that I'd like to loop through within the multi line string. I am not sure what the syntax is for this. Something like below...
def html = """\
<ul>
<li>$awaiting.each { it.toPermalink()}</li>
</ul>
"""
Upvotes: 2
Views: 3081
Reputation: 66059
Have you considered using a MarkupBuilder? They provide a really nice way of constructing HTML or XML, especially if you want to embed looping constructs or conditional logic.
For example:
import groovy.xml.MarkupBuilder
def writer = new StringWriter()
def builder = new MarkupBuilder(writer)
def awaiting = ['one', 'two', 'three']
builder.html {
ul {
awaiting.each {
li(it.toString())
}
}
}
println writer.toString()
Results in:
<html>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</html>
Upvotes: 1
Reputation: 171084
The following:
class PLink {
String name
String toPermalink() {
"link->$name"
}
}
def awaiting = [ new PLink( name:'one' ), new PLink( name:'two' ), new PLink( name:'three' ) ]
def html = """<ul>
<li>${awaiting.collect { it.toPermalink() }.join( "</li><li>" )}</li>
</ul>"""
Produces this output:
<ul>
<li>link->one</li><li>link->two</li><li>link->three</li>
</ul>
It basically calls the method on each element, collects
the results back into another list, and then joins
the list together into a string
Upvotes: 6