Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 347
Ula Krukar Avatar asked Jan 10 '11 10:01

Ula Krukar


1 Answers

Here's what I did, which seems to work in most scenarios:

The default value should be an empty string, and the null-check should be ?has_content.

<#function someFunction optionalParam="" >
    <#if (optionalParam?has_content)>
        <#-- NOT NULL -->
    <#else>
        <#-- NULL -->
    </#if>
</#function>
like image 129
Scott Rippey Avatar answered Nov 07 '22 04:11

Scott Rippey