简体   繁体   English

来自字符串的MarkupBuilder渲染

[英]MarkupBuilder Rendering From String

I'm using MarkupBuilder to render some HTML from a taglib like so (stripped down for clarity): 我正在使用MarkupBuilder从taglib渲染一些HTML,如下所示(为了清晰起见,将其删除):

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)... 现在假设在form()内的某个地方,我想插入用户指定的某些元素,因此在文件系统上的文件中,我有类似的内容(再次简化)。

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? 我的问题是,如果我读到select in in a String,taglib是否有一种方法可以将其解析为Groovy并将其作为MarkupBuilder实例的一部分?

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 更好的方法可能是使用GroovyTemplateEngine将值注入格式化的完整标记中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM