2

我定义了以下变量:

def VAL1 = 'foo'
def VAL2 = 'bar'

def s2 = 'hello ${VAL1}, please have a ${VAL2}'

使这种替换起作用的最简单方法是什么?我如何构建 GStrings2并对其进行评估?(VALs 和 s2 是从数据库中加载的,此代码段仅用于演示我的问题。)

4

2 回答 2

6

如果可以SimpleTemplateEngine将变量放入 Map?

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()
于 2011-06-15T10:11:15.763 回答
1

那么:

def VAL1 = 'foo'
def VAL2 = 'bar'

def s2 = "hello ${VAL1}, please have a ${VAL2}".toString()

?

注意:注意双引号

于 2011-06-15T10:16:20.300 回答