Question

I'm using MarkupBuilder to render some HTML from a taglib like so (stripped down for clarity):

def formContainer = new MarkupBuilder(out)
formConainer.form() {
   input() { }
   input() { }
}

Now assume that somewhere inside the form() I want to pull in some elements specified by a user so in a file on the file system I have something like this (again, simplified)...

select() {
  option()
  option()
}

My question is, if I read that select in as a String, is there a way for the taglib to parse it as groovy and make it part of the MarkupBuilder instance?

def formContainer = new MarkupBuilder(out)
formConainer.form() {
   input() { }
   input() { }

   // I want the select to render here
}
Était-ce utile?

La solution

One method for doing this would be:

String externalMarkup = '''
select() {
  option()
  option()
}
'''
def out = new StringWriter()

def formContainer = new groovy.xml.MarkupBuilder( out )
formContainer.form() {
   input()
   input()

   // Wrap the string in { -> ... } to make it a closure, and evaluate it
   def extern = new GroovyShell().evaluate( "{ it-> ${externalMarkup} }" )
   // Set the delegate of this closure to the MarkupWriter
   extern.delegate = formContainer
   // Then execute the closure
   extern()
}
println out.toString()

However, this feels brittle to me...

A better method might be to use the GroovyTemplateEngine to inject your values into a formatted complete bit of markup

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top