java 参数可以为空的 Freemarker 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4645784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Freemarker function with parameter that can be empty
提问by Ula Krukar
I created function in Freemarker:
我在 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)}
.
我这样称呼它:${formatDate(object.someDate)}
.
It all works until someDate
is null. In that case I get exception:
这一切都有效,直到someDate
为空。在这种情况下,我得到异常:
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.
我怎样才能做到这一点?如果参数值为空,我希望该函数正常工作。
采纳答案by Ula Krukar
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>
回答by Scott Rippey
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.
默认值应为空字符串,空检查应为?has_content。
<#function someFunction optionalParam="" >
<#if (optionalParam?has_content)>
<#-- NOT NULL -->
<#else>
<#-- NULL -->
</#if>
</#function>
回答by TheYann
Freemarker doesn't really handle the null values very well.
Freemarker 并不能很好地处理空值。
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:
我总是使用参数上的 ?has_content 来检查那里是否有东西。其他参数检查器也不总是能很好地处理空值,所以我建议如下:
<#if anyDate?has_content && anyDate?is_date>
just to be sure.
只是要确定。