需求非常简单:用当前执行上下文解析字符串。
示例:
def templateToResolve = "${hello}" // This comes from a function, the variable is not resolved here
def hello = "world"
// How to "resolve" templateToResolve without knowing the existence of hello
println templateToResolve // world
也许我们可以提取执行上下文的绑定并将其与 StreamingTemplateEngine 一起使用,但我没有找到获取当前绑定的方法。 我还查看了 Eval.me,但 Eval 不使用外部上下文。 我什至检查了动态编译没有成功。
解决方案不得以任何方式使用 hello var,它必须是动态的。
所以底线是不能使用 GString(即“${hello}”)。您在 GString 中引用的变量必须在定义它们的上下文中可见。现在你可以用它来做一些奇特的事情,比如将 GString 转换成其他表示形式,如下所示:
def hello = "world"
def x = "Guy ${hello} Hi"
println( x.getStrings() )
println( x.getValues() )
StringBuilder builder = new StringBuilder()
String[] gstr = x.getStrings()
String[] gVals = x.getValues()
for( int i = 0; i < gstr.length; i++ ) {
String curr = gstr[i]
int valueIndex = i - 1
if( valueIndex >= 0 ) {
builder.append("`")
builder.append( gVals[i-1] )
builder.append("`")
}
builder.append( curr )
}
println( builder.toString() )
但我不知道这是否是你想要的。我想您可能想看看
SimpleTemplateEngine
,它可以让您定义所需的模板,而无需嵌入其中的上下文。像这样:
def text = 'Dear "$firstname $lastname",\nSo nice to meet you in <% print city %>.\nSee you in ${month},\n${signed}'
def binding = [firstname:"Sam",
lastname:"Pullara",
city:"San Francisco",
month:"December",
signed:"Groovy-Dev"]
def engine = new groovy.text.SimpleTemplateEngine()
def template = engine.createTemplate(text).make(binding)
def result = 'Dear "Sam Pullara",\nSo nice to meet you in San Francisco.\nSee you in December,\nGroovy-Dev'
assert result == template.toString()
有关完整讨论,请参阅模板引擎
上的 Groovy 文档