Paul
Paul

Reputation: 393

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

Upvotes: 6

Views: 2059

Answers (2)

dpr
dpr

Reputation: 10972

Another more elegant way, without the need to specify all parameters, would be to add a "fake binding" as default to your parameters map. The default will be used, if there is no matching key in the parameters, and will simply replace the placeholder with itself:

class FakeBinding {
  private def value

  FakeBinding(x) {
    value = x;
  }

  def propertyMissing(x) {
    return new FakeBinding(value + '.' + x);
  }

  String toString() {
    '${' + value + '}'
  }
}

And use this as default

def parameters = [:].withDefault { key -> new FakeBinding(key) }
parameters["PARAM1"] = "VALUE1"
parameters["PARAM2"] = "VALUE2"

def templateEngine = new SimpleTemplateEngine()
def output = templateEngine.createTemplate(template).make(parameters)
print output

Upvotes: 0

dsharew
dsharew

Reputation: 10665

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

Upvotes: 4

Related Questions