我对此有类似的疑问:
Groovy string interpolation with value only known at runtime
可以完成以下工作:
def message = 'Today is ${date}, your id is: ${id}';
def date1 = '03/29/2019'
def id1 = '12345'
def result = {date, id -> "${message}"}
println(result(date1, id1))
因此,我想获取一个已经在其他地方定义的字符串(为简单起见,在此将其定义为“消息”),并已在其中嵌入内插的$ {date}和$ {id},并在此处进行处理使用闭包以及输入字段的定义。
我尝试了各种更改,在闭包中定义消息时不使用“ $ {}”,使用单引号或双引号,在插值变量周围将双引号嵌入字符串“ message”中,等等,我总是得到这个结果:
Today is ${date}, your id is: ${id}
但是我想说:
Today is 03/29/2019, your id is: 12345
以下方法有效,但我不确定这是否是最佳方法:
def message = '"Today is ${date}, your id is: ${id}"'
def sharedData = new Binding()
def shell = new GroovyShell(sharedData)
sharedData.setProperty('date', '03/29/2019')
sharedData.setProperty('id', '12345')
println(shell.evaluate(message))
http://docs.groovy-lang.org/latest/html/documentation/guide-integrating.html
答案 0 :(得分:2)
ernest_k是正确的,您可以为此使用模板引擎:
import groovy.text.SimpleTemplateEngine
def templatedMessage = new SimpleTemplateEngine().createTemplate('Today is ${date}, your id is: ${id}')
def date1 = '03/29/2019'
def id1 = '12345'
def result = { date, id -> templatedMessage.make(date: date, id: id)}
println(result(date1, id1))