Search code examples
freemarker

How to define a freemarker function?


I define a freemarker function, such as:

<#function ehtml str>
    <#if (str??) >
        <#return str?html>
    <#else>
        <#return "">
    </#if>
</#function>

I try to check the 'str' is not exist using <#if (str??) >, But it does not work. I still get a error "required parameter: str is not specified." when the paramter is null.


Solution

  • Because the str parameter is required according that function definition, it doesn't even reach the <#if str??> line (BTW that () is redundant there). Right now the only way to make it non-required is providing a default for it, like <#function ehtml str=''>. So actually this function could be written as <#function ehtml str=''><#return str?html></#function>. Indeed, the best would be if you just to write ${foo!?html} where you expect a null, instead of the longer ${ehtml(foo)}. That's why FTL has the maybeNull!/ maybeNull!default operator after all. So then you don't need this function.