[freemarker] Handling null values in Freemarker

How to handle null values in Freemarker? I get some exceptions in the template when null values are present in data.

This question is related to freemarker

The answer is


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.


If you have a lot of variables to convert in optional, you can use SubimeText with this:

Find: \${([A-Za-z_0-9]*)}
Replace: \$\{${1}!\}

Be sure regex and case-sensitive options are enabled:

Sublime regex replace


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>