我定义了以下变量:
def VAL1 = 'foo'
def VAL2 = 'bar'
def s2 = 'hello ${VAL1}, please have a ${VAL2}'
什么是使这种替代有效的最简单方法?如何从s2
构建GString并对其进行评估?(VAL和s2是从数据库加载的,此片段仅用于演示我的问题。)
如果可以将变量放入Map中,则可以使用SimpleTemplateEngine
?
import groovy.text.SimpleTemplateEngine
def binding = [ VAL1:'foo', VAL2:'bar' ]
def template = 'hello ${VAL1}, please have a ${VAL2}'
println new SimpleTemplateEngine().createTemplate( template ).make( binding ).toString()
编辑
您可以使用绑定而不是映射,因此以下操作在groovyconsole中有效:
// No def. We want the vars in the script's binding
VAL1 = 'foo'
VAL2 = 'bar'
def template = 'hello ${VAL1}, please have a ${VAL2}'
// Pass the variables defined in the binding to the Template
new SimpleTemplateEngine().createTemplate( template ).make( binding.variables ).toString()
以及:
def VAL1 = 'foo'
def VAL2 = 'bar'
def s2 = "hello ${VAL1}, please have a ${VAL2}".toString()
注意:注意的双引号