Search code examples
groovyinterpolationgstring

Groovy string interpolation when string is defined before the interpolated variables are defined


I have a similar question to this:

Groovy string interpolation with value only known at runtime

What can be done to make the following work:

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))

So I want to take a string that has already been defined elsewhere (for simplicity I define it here as 'message'), having the interpolated ${date} and ${id} already embedded in it, and process it here using the closure, with definitions for the input fields.

I've tried this with various changes, defining message in the closure without the "${}", using single or double quotes, embedding double quotes around the interpolated vars in the string 'message', etc., I always get this result:

Today is ${date}, your id is: ${id}

But I want it to say:

Today is 03/29/2019, your id is: 12345

The following worked but I am not sure if it is the best way:

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


Solution

  • ernest_k is right, you can use the templating engine for exactly this:

    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))