tags:

views:

147

answers:

3

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>
     """
+3  A: 

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

tim_yates
A: 

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>
ataylor
A: 

This is brilliant...

Is there a way to make the work as a parameter i.e.

builder.html{
tag{
    awaiting.each{}
    }
} return result

where tag is ul or ol depending on what is sent to it???

john renfrew