Handling null values in Freemarker

前端 未结 5 2079
时光说笑
时光说笑 2020-12-07 22:19

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

相关标签:
5条回答
  • 2020-12-07 22:54

    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

    0 讨论(0)
  • 2020-12-07 22:55

    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>
    
    0 讨论(0)
  • 2020-12-07 23:02

    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"}
    
    0 讨论(0)
  • 2020-12-07 23:06

    If you have a lot of variables to convert in optional, you can use SubimeText with this:

    Find: \${([A-Za-z_0-9]*)}
    Replace: \$\{${1}!\}
    

    Be sure regex and case-sensitive options are enabled:

    0 讨论(0)
  • 2020-12-07 23:07

    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.

    0 讨论(0)
提交回复
热议问题