2

I have the following variables defined:

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

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

What is the easiest way to make this substitution work? How could I build a GString from s2 and have it evaluated? (VALs and s2 are loaded from database, this snippet is only for demonstrating my problem.)

jabal
  • 11,987
  • 12
  • 51
  • 99

2 Answers2

6

You can use the SimpleTemplateEngine if you can get your variables into a 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()

edit

You can use the binding instead of the map, so the following works in the 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()
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • my problem is that VAL1 and VAL2, .. VALn variables are not in a map. I do not even know their exact number. – jabal Jun 15 '11 at 10:13
  • @jabal Can you edit your question to give a better example? If you don't know what variables you are getting, how do you know what template to use? – tim_yates Jun 15 '11 at 10:20
  • @jabal Added another possible solution, using the binding (where your variables should already be declared) as the Map for the template – tim_yates Jun 15 '11 at 10:28
1

and what about :

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

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

?

Note : notice the double quotes

Grooveek
  • 10,046
  • 1
  • 27
  • 37
  • Ok, but from the database I get a simple string, not a GString. That's why I used single quotes. I have to do the substitution after having this variable defined.. :-) – jabal Jun 15 '11 at 10:32