Refactoring groovy html markupbuilder

732 Views Asked by At

I picked up groovy scripting recently so I'm still a beginner in it (I'm also a professional programmer in C with some notions of Java) I successfully created a valid html page with the MarkupBuilder (see simplified example below)

def writer = new StringWriter()
def page_html = new groovy.xml.MarkupBuilder(writer)
page_html.html
{
    head
    {
        title("Test HTML table")
    }
    body
    {
        h3("Test HTML")
        a 
        {
            mkp.yield("Hello html")
        }
    }
}
writer.toString()

All is fine except now the "body" part gets quite large and I have some code repeating so it really needs refactoring. By refactoring, I mean I want to put parts in a function/procedure and call it repeatedly in the "body".

I tried to follow this example http://groovy.jmiguel.eu/groovy.codehaus.org/Using+MarkupBuilder+for+Agile+XML+creation.html

Thinking it would work with HTML markup the same as XML. EDIT : it does work.

For example if I do something like

def my_procedure(builder)
{
   builder.a 
   {
        mkp.yield("Hello html")
   }
}

and

def writer = new StringWriter()
def page_html = new groovy.xml.MarkupBuilder(writer)
page_html.html
{
    head
    {
        title("Test HTML table")
    }
    body
    {
        h3("Test HTML")
        my_procedure(page_html)
    }
}
writer.toString()

EDIT: you get a failure at execution if don't write builder.a but only "a" in the procedure

Thanks, Clement

0

There are 0 best solutions below