简体   繁体   中英

Replacing a string in a template with Groovy

I have a text file which serves as a "template" and looks like something this:

[...]
<data>${payload}</data>
[...]

In a Groovy script I would now like to load this template and ${payload} being replaced with a specific value from the script.

Pseudo code:

def payload = "Hello world"
def f = new File(filename)
println f.text

So that the result would be:

<data>Hello world</data>

I have looked at Groovy templates but I don't really get it.

You can indeed use groovy template engines, which allows you to have some parametrized text. You define a structure and then you populate it with the information you want

    def text = '<h1>${title}</h1><data>${payload}</data>'

    def binding = ["title":"My Title", "payload":"Hello world"]

    def engine = new groovy.text.SimpleTemplateEngine()
    def template = engine.createTemplate(text).make(binding)
    println template.toString() // <h1>My Title</h1><data>Hello world</data>
String templateInterpolator(String text, Map model) {
  new groovy.text.SthenimpleTemplateEngine()
    .createTemplate(text)
    .make(model)    
    .toString()
}

then:

assert templateInterpolator('Hello ${name}', [name: 'World']) == 'Hello World'

another example:

assert templateInterpolator('''
Dear ${env.receiver}, 
This is about ${env.topic}
Best Regards,
${env.sender}

''', [env:[receiver: 'Ali', sender: 'Omar', topic: 'My love to you']]) == '''
Dear Ali, 
This is about My love to you
Best Regards,
Omar

'''

 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM