3

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

Steve T
  • 165
  • 11
  • 2
    I'm not very sure of this, but I think [Simple template engine](http://docs.groovy-lang.org/docs/next/html/documentation/template-engines.html#_simpletemplateengine) may be a more lightweight approach for this – ernest_k Mar 29 '19 at 17:54

1 Answers1

3

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))
tim_yates
  • 167,322
  • 27
  • 342
  • 338