1

I am using freemarker 2.3.x. It is expected that not all variables are defined. And it is needed to be output as it is. For example, the template is

${a}
${b}

And the data model is a=name. Then the output is expected to be

name
${b}

By using TemplateExceptionHandler.IGNORE_HANDLER, the output will not contain ${b}

For now I am adding a new entry b=${b} to data model. It works but it is kind of ugly workaround. And I need to know exactly how many undefined variable will there be which is a limitation.

Is there a setting or a way to do that?

DeepNightTwo
  • 4,809
  • 8
  • 46
  • 60

2 Answers2

2

I had the same question and found another way to skip variables you know are not in your data-model.

This template should print ${b}:

${a}
${r"${b}"}

result:

name
${b}

https://stackoverflow.com/a/5207658/2618186

I would love to see how exactly your reprinting function looks like though. Might be nicer.

R. Sluiter
  • 162
  • 1
  • 1
  • 13
1

Maybe the least horrible way to solve this is on the data-model level. Only you shouldn't add "b=${b}" and such manually, instead, you should use a custom TemplateHashModelEx as the data-model (the "root"), which does that automatically. (That has the annoying side effect that Configuration-level shared variables, if you have any, will be hidden by the data-model root.)

Anyway, even in theory, it's quite impossible to solve correctly. Consider, what if you have ${a + b} where a is present and b is missing. Well, it could be render as ${123 + b} then, but you see things become involved. Ad then, what if you have ${a(b)}, where a is present but not b, and then in a later iteration a is missing but b is present...

As of TemplateExceptionHandler-s, while you could re-print the failing expression when it was an InvalidReferenceException, as out.write("${" + te.getBlamedExpressionString() + "}");, it won't work for non trivial interpolations. Like for the ${a + b} example, it would print ${b}, silently removing the a +.

ddekany
  • 29,656
  • 4
  • 57
  • 64
  • Not working in ${a + b} case is not a big issue. Thanks for your solution. re-print the failing expression would be the good-enough solution for me. – DeepNightTwo Apr 22 '17 at 14:49