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: f开发者_运维知识库ormatDate required parameter: anyDate is not specified.
How can I do this? I want the function to work if parameter values is null.
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>
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>
Freemarker doesn't really handle the null values very well.
I always use the ?has_content on the params to check if there is something in there. The other parameter checkers don't always handle the null value well either so I would suggest something like this:
<#if anyDate?has_content && anyDate?is_date>
just to be sure.
精彩评论