Kartikey Joshi Kartikey Joshi - 2 months ago 16
Groovy Question

Groovy - Append values to variables in a string

Lets assume I have a domain class called Template that looks somewhat like this:

class Template{
String subject
...
}


I save an instance of this class:

Template t=new Template(subject:'Hello ${name}').save()


Now, I fetch this instance inside a method as follows:

def render(Long id){
String name='foo'
Template t= Template.get(id)
println t.subject
}



I want the "println t.subject" to be printed as "Hello foo". What I get is "Hello ${name}".
I want t.subject to dynamically replace the value of variable name - "foo" in place of ${name}.


Can this be achieved in groovy?
I cannot find any documentation of how to do this, or why this cannot be done.

Update:

I tried this on my GroovyConsole.

class Entity{
String name
}

class Template{
String name
String subject
}

String renderTemplate(Template template, Entity entity){
return template.subject
}

Entity e = new Entity(name:'product')
Template template=new Template(name:'emailTemplate',subject:'Product ${e.name}')

renderTemplate(template,e)


The Output I got was:


Result: Product product

Answer
class Template {
  String subject
  // ...
}

Template t = new Template(subject: 'Hello, ${name}').save()

Important: Use single quotes in 'Hello, ${name}' or you will get an error.

def render(Long id) {
  String name = "world"
  Template t = Template.get(id)

  ​def engine = new groovy.text.GStringTemplateEngine()

  def subject = engine
    .createTemplate(t.subject)
    .make(name: name)​

  println subject
}
Comments