xpt
xpt

Reputation: 23084

Groovy to use variables as template

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?

Upvotes: 1

Views: 930

Answers (3)

cfrick
cfrick

Reputation: 37073

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!

Upvotes: 1

daggett
daggett

Reputation: 28644

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

Upvotes: 3

Andrej Istomin
Andrej Istomin

Reputation: 3043

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"

Upvotes: 0

Related Questions