smeeb
smeeb

Reputation: 29537

Binding Groovy TemplateEngine with any variable names

I am trying to write a method that:

  1. Loads a template file (*.tpl) from the local file system
  2. Parameterizes that template file with a list of supplied variables

Best attempt thus far:

String loadParameterizedTemplateByName(String templateName,
        String... variables) {
    InputStream inputStream = 
        this.class.classLoader.getResourceAsStream(templateName)
    StringWriter writer = new StringWriter()
    IOUtils.copy(inputStream, writer, 'UTF-8')
    String templateBody = writer.toString()

    def binding = variablesAsBinding(variables) // ?!?!

    engine.createTemplate(templateBody).make(binding).toString()
}

So for instance say I have the following HelloEmail.tpl template file:

HelloEmail.tpl
==============
Hello ${firstName},

You are awesome! ${someGuy} even says so!

Sincerely,
${me}

Then my desired invocation of this would be:

String firstName = 'John'
String someGuy = 'Mark'
String me = '@smeeb'
String parameterizedTemplate = 
    loadParameterizedTemplateByName('HelloEmail.tpl', firstName, someGuy, me)

So that the final result is that parameterizedTemplate string has a value of:

println parameterizedTemplate
// Prints:
Hello John,

You are awesome! Mark even says so!

Sincerely,
@smeeb

The trick here is that the method needs to be able to use any list of supplied variables against any supplied template file!

Is this possible to accomplish via reflection? Meaning the TemplateEngine just looks as the supplied list of String variables, and substitutes them for variables of the same name (as found in the template)?

Upvotes: 2

Views: 569

Answers (1)

tim_yates
tim_yates

Reputation: 171114

You can pass a Map like so:

import groovy.text.markup.MarkupTemplateEngine
import groovy.text.markup.TemplateConfiguration

String loadParameterizedTemplateByName(Map variables, String templateName) {
    def engine = new groovy.text.SimpleTemplateEngine()
    this.class.getResource(templateName).withReader { reader ->
        engine.createTemplate(reader).make(variables)
    }
}

def result = loadParameterizedTemplateByName('/mail.tpl', firstName:'Tim', someGuy:'StackOverflow', me:'smeeb')

assert result == 'Hello Tim,\n\nYou are awesome! StackOverflow even says so!\n\nSincerely,\nsmeeb'

Upvotes: 4

Related Questions