Freemarker function with a parameter that may be empty

I created a function in Freemarker:

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

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

Everything works up to someDate . In this case, I get an exception:

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

How can i do this? I want the function to work if the parameter values ​​are zero.

+7
source share
3 answers

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>
+5
source

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

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

 <#function someFunction optionalParam="" > <#if (optionalParam?has_content)> <#-- NOT NULL --> <#else> <#-- NULL --> </#if> </#function> 
+10
source

Freemarker does not handle null values ​​very well.

Do I always use? Has_content for parameters to check if there is something there. Other parameter checking tools also do not always handle a null value well, so I would suggest something like this:

 <#if anyDate?has_content && anyDate?is_date> 

just to make sure.

+1
source

All Articles