1

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

6
  • With groovy 2.4.5 it returns correct result.
    – Opal
    Commented Dec 1, 2015 at 8:11
  • You might also be interested in the MarkupTemplateEngine. It would allow you to define a base template class that contains your utility methods, while being significantly faster.
    – melix
    Commented Dec 1, 2015 at 8:18
  • @Opal my bad, I got it right in the post but wrong in my code (a builder.td was missing) so I edited the post to reflect that. To melix thanks for the suggestion. I saw some bits about using a template around the web but it seems a bit too advanced for me right now
    – CMFR
    Commented Dec 1, 2015 at 9:53
  • @CMFR How would you like it to work? You need to invoke a in some context. So builder.a will be ok, or builder.with { a// some code}.
    – Opal
    Commented Dec 1, 2015 at 10:40
  • 1
    @CMFR, so please provide an example that shows the real problem.
    – Opal
    Commented Dec 1, 2015 at 11:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.