Denis Kulagin
Denis Kulagin

Reputation: 8937

StringTemplate: how to detect, if variable in tempate is not explicitly set?

I am using StringTemplate to auto-generate configuration files and it's an error, if user haven't defined some of the variables.

StringTemplate will replace undefined variables (I mean $var$) with empty string and error will remain undetected. E.g.:

some_property=$some_property$

is rendered into:

some_property=

How to force StringTemplate to raise exception, if variable in template is not explicitly defined using

StringTemplate.setAttribute(key, value)

?

Upvotes: 0

Views: 1383

Answers (1)

Volker Stampa
Volker Stampa

Reputation: 849

With StringTemplate 4 the error listener is informed about an undefined attribute. With a custom error-listener you can handle this as required. For example:

    ST tmp = new ST("Hello <name>!");

    tmp.write(new NoIndentWriter(new StringWriter()), new STErrorListener() {

        @Override
        public void runTimeError(STMessage msg) {
            if(msg.error == ErrorType.NO_SUCH_ATTRIBUTE)
              System.out.println("Attribute not defined: "+ msg.arg);
        }

        @Override public void compileTimeError(STMessage msg) { }
        @Override public void IOError(STMessage msg) { }
        @Override public void internalError(STMessage msg) { }
    });

Upvotes: 1

Related Questions