How to check if a variable exists in a FreeMarker template? How to check if a variable exists in a FreeMarker template? java java

How to check if a variable exists in a FreeMarker template?


To check if the value exists:

[#if userName??]   Hi ${userName}, How are you?[/#if]

Or with the standard freemarker syntax:

<#if userName??>   Hi ${userName}, How are you?</#if>

To check if the value exists and is not empty:

<#if userName?has_content>    Hi ${userName}, How are you?</#if>


This one seems to be a better fit:

<#if userName?has_content>... do something</#if>

http://freemarker.sourceforge.net/docs/ref_builtins_expert.html


Also I think if_exists was used like:

Hi ${userName?if_exists}, How are you?

which will not break if userName is null, the result if null would be:

Hi , How are you?

if_exists is now deprecated and has been replaced with the default operator ! as in

Hi ${userName!}, How are you?

the default operator also supports a default value, such as:

Hi ${userName!"John Doe"}, How are you?