Reputation: 167
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.
Upvotes: 0
Views: 600
Reputation: 3894
As ddekany says, if you use named function parameters, you need to specify a default value to make the parameter optional, if you really want "null" values to get into your function (because even if passed to the function, but "null", the param will assume the default value) and handle them there, you can use a trick (kinda like JS) with the rest... param which can only be used as the last (or only as you'll see) parameter and will contain a sequence (array) of all parameters passed to the function, so instead of using named parameters you would do something like this:
<#function ehtml(args...)>
<#local str = args[0] />
<#if !str??>
<#-- first parameter was null -->
<#return '' />
</#if>
<#-- do other stuff -->
<#return str?html />
</#function>
for your use case a default value of an empty string ''
is completely fine though, as that is what you would return anyways...but then you also do not need the check for null!
and yes, you can write FreeMarker functions like that <#function fn(param1, param2)>
instead of <#function fn param1 param2>
, it's not documented, but it works exactly the same (at least as of v2.3.26) and I prefer it, as it is closer to Java/JavaScript syntax...
Upvotes: 0
Reputation: 31152
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.
Upvotes: 2