htmlgroovybuildergroovlet

How do I delegate building to a method?


I am writing a Groovlet and would like to delegate part of the HTML builder to a method but am having trouble getting it to work. Below is what I have:

def pages = [page1: html.p("page1")]
html.html {
  p("p")
  pages[page1]
}

I am expecting the following output:

<html>
  <p>p</p>
  <p>page1</p>
</html>

Instead what I get is the following:

<p>text</p> 
<html> 
  <p>p</p>
</html>

What am I doing wrong?


Solution

  • I'm not overly familiar with the builder in question but I'd expect to be doing something like:

    def pages = [page1: { p("page1") }]
    html.html {
       p("p")
       delegate.with pages[page1]
    }
    

    Instead of pages[page1], of course, you could call any closure or a .&'d method.

    You need the delegate.with so that the closure you're running has its method calls (like p()) resolved to the delegate of the closure running it (that is, the HtmlBuilder).