How to ignore missing options in a Groovy template template

I have a template with placeholders (ex $ {PARAM1}), the program successfully resolves them. But what if I want to allow only placeholders, which I go to the template engine, and leave the other $ {} ignored? Currently, a program crashes if it cannot 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}

thank

+4
source share
1 answer

Honestly, I'm not sure if the groovy template engine supports a way to ignore parameters; (leaving the placeholder as it is when the corresponding parameter is missing), but here's the 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
+1
source

Source: https://habr.com/ru/post/1677353/


All Articles