Home > Software design >  Groovy to use variables as template
Groovy to use variables as template

Time:09-06

In Groovy, is it possible to define variables as template first then use them later?

Like predefine body before knowing the content of subject:

body = 'Hello, ${subject}!'
subject = "World"

Then get Hello, World! from the body template (after the content of subject is defined) somehow?

CodePudding user response:

https://docs.groovy-lang.org/latest/html/api/groovy/text/SimpleTemplateEngine.html

def body = 'Hello, ${subject.toUpperCase()}!'

def engine = new groovy.text.SimpleTemplateEngine()
def template = engine.createTemplate(body) // heavy operation - better to cache it

def binding = [
    subject: 'world'
]

println template.make(binding).toString()

println template.make(subject: 'john').toString()

output:

Hello, WORLD!
Hello, JOHN!

more examples here:

https://docs.groovy-lang.org/docs/next/html/documentation/template-engines.html

CodePudding user response:

I am not aware of such a feature in Groovy, but usually it is not that difficult to solve the problem by using String.replaceAll method:

def bodyTemplate = 'Hello, ${subject}!'
def subject = "World"
def body = bodyTemplate.replaceAll('\\$\\{subject}', subject)
println "body = $body"

CodePudding user response:

You can use a closure inside a GString, so instead of capturing the value on creation of the GString, it gets evaluated when it has to manifest into a string.

body = "Hello, ${-> subject}!"
subject = "World"

println body
// → Hello, World!
  • Related