Reputation: 3085
How to handle null
values in Freemarker? I get some exceptions in the template when null
values are present in data.
Upvotes: 108
Views: 210887
Reputation: 316
Use:
${(user.isSuperman!false)?c}
It will work when "isSuperman" is null and when have boolean value
What we want:
What we know:
Upvotes: 1
Reputation: 189
I would like to add more context if you have issues and this is what I have tried.
<#if Recipient.account_type?has_content>
… (executes if variable exists)
<#else>
… (executes if variable does not exist)
</#if>
This is more like Javascript IF and ELSE concept where we want to check whether this value or another chaining through required logic.
Scenario: Customer has ID and name combined like 13242 Harish, so where our stakeholder need the only name, so I have tried this ${record.entity?keep_after(" ")} and it did work, however, it can only work when you have space, but when a customer doesn't have space and one name, I had to do some IF ELSE condition to check Null value.
Upvotes: 1
Reputation: 15962
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
Upvotes: 120
Reputation: 5852
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>
Upvotes: 1
Reputation: 307
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.
Upvotes: 5
Reputation: 7439
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"}
Upvotes: 141