Missing & null values in FreeMarker templates

Managed by | Updated .

Special care must be taken when displaying values in a template that the value isn't missing or evaluates to null as it will result in a FreeMarker error.

An approach to prevent this is to check that a value exists before displaying it using the ?? construct:

<#-- INCORRECT -->
<p class="description">${s.result.metaData["c"]}</p>

<#-- CORRECT -->
<#if s.result.metaData["c"]??><p class="description">${s.result.metaData["c"]}</p></#if>

Alternatively the ! construct can be used to fall back to a default value. For example ${author!"N/A"} will display the author, or fall back to "N/A" if the author doesn't exist.

<#-- INCORRECT -->
<p class="description">${s.result.metaData["c"]}</p>

<#-- CORRECT usage -->
<#-- with explicit default value -->
<p class="description">${s.result.metaData["c"]!"My default"}</p></#if>

<#-- with implicit default value (empty string) -->
<p class="description">${s.result.metaData["c"]!}</p></#if>

<#-- When using modifiers, use brackets to explicitly define scope around the base value and the '!' value -->
<p class="description">${(s.result.metaData["c"]!"My default")?lower_case?replace("donotwant", "")}</p></#if>

Additional resources

Was this artcle helpful?

Tags
Type:
Features: Frontend > Templating Frontend > Freemarker

Comments