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

Dónal picture Dónal · Nov 20, 2008 · Viewed 245.3k times · Source

I have a Freemarker template which contains a bunch of placeholders for which values are supplied when the template is processed. I want to conditionally include part of the template if the userName variable is supplied, something like:

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

However, the FreeMarker manual seems to indicate that if_exists is deprecated, but I can't find another way to achieve this. Of course, I could simple providing an additional boolean variable isUserName and use that like this:

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

But if there's a way of checking whether userName exists then I can avoid adding this extra variable.

Answer

Ulf Lindback picture Ulf Lindback · Nov 20, 2008

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>