开发者

Nullable date in Freemarker

This is a piece of my freemarker template:

${order.needByDate?if_exists?date}

I want it to work as following:

  • if needByDate is null, then write nothing
  • if it is not null, then write the date part

The above works only in second scenario. What is the 开发者_如何学编程correct way to achieve this?


This should also work

${(order.needByDate?date)!}

The parentheses are necessary

You can also add a default value such as "n/a" like this

${(order.needByDate?date)!"n/a"}


There may be a smarter way of doing this but the following should do the job.

<#if order.needByDate??>${order.needByDate?date}</#if>


A solution that considers null and empty-string values:

For Freemarker version 2.3.23 or newer:

${aDateField?has_content?then(aDateField?datetime?string["MM/dd/yyyy hh:mm:ss"],"")}

For older versions:

<#if aDateField?has_content>
${aDateField?datetime?string["MM/dd/yyyy hh:mm:ss"]}
</#if>

You can test it at https://try.freemarker.apache.org/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜