Handling null values in Freemarker

妖精的绣舞 提交于 2019-11-28 16:55:14

问题


How to handle null values in Freemarker? I get some exceptions in the template when null values are present in data.


回答1:


You can use the ?? test operator:

This checks if the attribute of the object is not null:

<#if object.attribute??></#if>

This checks if object or attribute is not null:

<#if (object.attribute)??></#if>

Source: FreeMarker Manual




回答2:


Starting from freemarker 2.3.7, you can use this syntax :

${(object.attribute)!}

or, if you want display a default text when the attribute is null :

${(object.attribute)!"default text"}



回答3:


I think it works the other way

<#if object.attribute??>
   Do whatever you want....
</#if>

If object.attribute is NOT NULL, then the content will be printed.




回答4:


Use ?? operator at the end of your <#if> statement.

This example demonstrates how to handle null values for two lists in a Freemaker template.

List of cars:
<#if cars??>
    <#list cars as car>${car.owner};</#list>
</#if>
List of motocycles:
<#if motocycles??>
    <#list motocycles as motocycle>${motocycle.owner};</#list>
</#if>


来源:https://stackoverflow.com/questions/13950289/handling-null-values-in-freemarker

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!