Anand B
Anand B

Reputation: 3085

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.

Upvotes: 108

Views: 210887

Answers (6)

Joter
Joter

Reputation: 316

Use:

${(user.isSuperman!false)?c}

It will work when "isSuperman" is null and when have boolean value

What we want:

  • For "null" we want to output 'false'
  • For boolean value and want to output value ('true' or 'false')

What we know:

Upvotes: 1

Harish
Harish

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.

Freemarker webite

Other reference:

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

Tom Verelst
Tom Verelst

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

Daniel Pern&#237;k
Daniel Pern&#237;k

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

Senthil Kumar Sekar
Senthil Kumar Sekar

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

Arnaud
Arnaud

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

Related Questions