Search code examples
groovytemplate-engine

How to ignore missing parameters in Groovy's template engine


I have a template with placeholders(e.x. ${PARAM1}), the program successfully resolves them. But what to do if I want to resolve only placeholders which I pass to template engine and leave other ${} ignored? Currently the program fails if it can't resolve all placeholders.

static void main(String[] args) {

    def template = this.getClass().getResource('/MyFile.txt').text

    def parameters = [
        "PARAM1": "VALUE1",
        "PARAM2": "VALUE2"
    ]
    def templateEngine = new SimpleTemplateEngine()
    def output = templateEngine.createTemplate(template).make(parameters)
    print output
}

File: ${PARAM1} ${PARAM2} ${PARAM3}

Thanks


Solution

  • To be honest I am not sure if the groovy templating engine supports a way of ignoring parameters; (leaving the placeholder as it is when the corresponding param is missing) but here is a hack.

    import groovy.text.*;
    
    def template = "\${PARAM1} \${PARAM2} \${PARAM3} \${PARAM4} \${PARAM5} \${PARAM6}"
    
    //example hard coded params; you can build this map dynamically at run time
    def parameters = [
        "PARAM1": "VALUE1",
        "PARAM2": "VALUE2",
        "PARAM3": null,
        "PARAM4": "VALUE4",
        "PARAM5": null,
        "PARAM6": "VALUE6"
    ]
    
    //this is the hack
    parameters.each{ k, v ->
       if(!v){
            parameters[k] = "\$$k"
        }
    }
    
    
    def templateEngine = new SimpleTemplateEngine()
    def output = templateEngine.createTemplate(template).make(parameters)
    print output
    

    Output:

    VALUE1 VALUE2 $PARAM3 VALUE4 $PARAM5 VALUE6