Freemarker - disable Syntax validation?

42 Views Asked by At

Is there an option to disable the ParseException?

I would have a HTML String which has an issue in the Syntax? The HTML String is created from my user, therefore there might be cases that the syntax is not correct. In those cases I just want to replace those variables to an empty string, like:

${message.} 

should be replace to ""

Because for this syntax I would get an ParseException:

Syntax error in template "htmlTemplate" in line 8, column 19: Encountered "}", but was expecting one of these patterns:

My goal is to have this use case:

  • User can create a HTML template with some variables (like ${myVariable}
  • Use Freemarker to replace those variables with "real values". -> This will exactly match my requirements, but the issue is currently it will not process the whole HTML code, since I got an Syntax error.

I´ve tried already with IGNORE_HANDLER, but this haven´t solved the issue

Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);

How can I solve this?

2

There are 2 best solutions below

5
Luuk On

The getting started has:

cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

and the note: I have suppressed the exceptions for the sake of simplicity. Don't do it in real products.

I have not tested what happens, but you could check to see if this works...

0
ddekany On

Sorry, you can't ignore syntax errors (assuming you want to allow any template constructs at all). The parser can't do that. TemplateExceptionHandler-s only handle runtime errors, that is, errors during template execution (which is later than parsing).

Also, if you could ignore syntax errors, that's certainly confusing for the user. Because, then things that are wrong just silently output nothing, and the user may not notice that the output is broken. When they do notice it, they still don't know why it didn't print anything, as they won't get any error details.