How to handle null
values in Freemarker? I get some exceptions in the template when null
values are present in data.
You can use the ??
test operator:
This checks if the attribute of the object is not null:
<#if object.attribute??></#if>
This checks if object or attribute is not null:
<#if (object.attribute)??></#if>
Source: FreeMarker Manual
Starting from freemarker 2.3.7, you can use this syntax :
${(object.attribute)!}
or, if you want display a default text when the attribute is null
:
${(object.attribute)!"default text"}
I think it works the other way
<#if object.attribute??>
Do whatever you want....
</#if>
If object.attribute
is NOT NULL, then the content will be printed.
Use ??
operator at the end of your <#if>
statement.
This example demonstrates how to handle null
values for two lists in a Freemaker template.
List of cars:
<#if cars??>
<#list cars as car>${car.owner};</#list>
</#if>
List of motocycles:
<#if motocycles??>
<#list motocycles as motocycle>${motocycle.owner};</#list>
</#if>
来源:https://stackoverflow.com/questions/13950289/handling-null-values-in-freemarker