Search code examples
javafreemarker

Freemarker function with parameter that can be empty


I created function in Freemarker:

<#function formatDate anyDate>
    <#assign dateFormat = read_from_configuration() />
    <#if anyDate??>
        <#return anyDate?date(dateFormat) />
    <#else >
        <#return '' />
    </#if>
</#function>

I call it like this: ${formatDate(object.someDate)}.

It all works until someDate is null. In that case I get exception:

Error executing macro: formatDate
required parameter: anyDate is not specified.

How can I do this? I want the function to work if parameter values is null.


Solution

  • In the end I did it like this:

    <#function formatDate anyDate='notSet'>
        <#assign dateFormat = read_from_configuration() />
        <#if anyDate?is_date>
            <#return anyDate?string(dateFormat) />
        <#else >
            <#return '' />
        </#if>
    </#function>