This article shows methods of handling NULL values and empty values within FreeMarker. FreeMarker is a templating language supported in the MessageGears Templates. More information about FreeMarker can be found in the FreeMarker documentation.
Encountering Null and Empty Values
Null values and Empty values are ever-present problems when working with data. Null values and empty values are commonly encountered within Accelerator due to missing data within the external datasource.
The has_content Function
FreeMarker has built-in functions to detect for variables. The most common method of detecting for empty or null values uses the has_content function and the trim function.
The has_content function, in the case of Accelerator, returns with a boolean value determining whether or not the provided variable exists. Using the function looks like this:
… (executes if variable exists)
… (executes if variable does not exist)
The has_content function is often used with another built-in FreeMarker function to detect for null values.
|Check the FreeMarker documentation for more information on the has_content function.|
The trim Function
The has_content function only checks to determine if the proper variable exists.
The trim function, used in a clever way, is often used to detect null values, empty values, or values populated with whitespace:
<#if Recipient.first_name?trim != ''> <!-- there is no space between quotes -->
… (executes if not null)
… (executes if null)
Using the trim function in this manner removes all whitespace from the variable. If anything is left over, then the value contains data. If the result of the trim is an empty string (identified by the ‘’), then the value is null.
Combining Functions and Best Practices
The best practice for handling null values and empty values is to combine the above functions. By itself, the has_content function does not return check for null or empty values. It only determines if the variable exists.
By itself, the trim function does not check if the variable exists. It only determines if the result, after trimming, is empty or not.
Combining these two functions in an IF statement is the recommended method of handling data.
<#if Recipient.last_purchase_date?has_content && Recipient.last_purchase_date?trim != ''>
… (executes if variable exists and is not null)
… (executes if variable does not exist OR variable is null)
This is a great way of identifying issues with data and setting a default value,
<#if Recipient.first_name?has_content && Recipient.first_name?trim != ''>
<#assign fname = Recipient.first_name>
<#assign fname = ‘Valued Customer’>