I have the following code where I assign the result of a Java method to a freemarker variable.
<#assign singleBenchmark = solverBenchmark.findSingleBenchmark(problemBenchmark)>
The problem is that return value of that Java method might null
. And even though I check if that variable isn't null
:
<#if !singleBenchmark??>
<td></td>
<#else>
<td>${singleBenchmark.score}</td>
</#if>
It still crashes on the <#assign ...>
line if that Java method returns null
, with this exception:
freemarker.core.InvalidReferenceException: Error on line 109, column 45 in index.html.ftl
solverBenchmark.findSingleBenchmark(problemBenchmark) is undefined.
It cannot be assigned to singleBenchmark
at freemarker.core.Assignment.accept(Assignment.java:111)
How can I avoid this exception without having to call the findSingleBenchmark
method multiple times in my ftl?
The normal way to handle unsafe APIs like this is with the !
(bang) operator:
<#assign singleBenchmark = solverBenchmark.findSingleBenchmark(problemBenchmark)!>
This is detailed in this section of the FreeMarker docs and the reasoning is given here.
If your snippet is the actual code, you may shorten it (significantly) to:
<td>${singleBenchmark.score!""}</td>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With