开发者

MarkupBuilder Rendering From String

I'm using MarkupBuilder to render some HTML from a taglib like so (stripped down for cla开发者_开发问答rity):

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
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜