pistacchio
pistacchio

Reputation: 58883

FreeMarker: Check if map value is null

I have a Map whose key and value and custom classes. The key class is called Position and is instantiated with two int (for example new Position(2, 4).

I got rid of this Position class and converted the map to a SimpleHash in order to use it with Freemarker. I now have a SimpleHash whose key is a String remapping Position values (for example "2 4") and whose value is either null or a Lot (custom) class.

In the template I need to check if the value of a given item in the SimpleMap (passed as map) is either null or a Lot instance.

        <#list mapMinY..mapMaxY as y>
            <tr>
                <#list mapMinX..mapMaxX as x>
                    <td>
                        <div>
                            <!-- Check if map[x + " " + y] is null -->
                            ${x}, ${y}
                        </div>
                    </td>
                </#list>
            </tr>
        </#list>

How to do this?

Upvotes: 4

Views: 9755

Answers (2)

ddekany
ddekany

Reputation: 31122

Use the ?? operator.

<#if map[x + " " + y]??>It's not null<#else>It's null or missing</#if>

See also the related part of the Manual.

Upvotes: 9

light_303
light_303

Reputation: 2111

since freemarker is kind of odd when it comes to null values have two ways to solve it. 1.Treat it as a missing value :

${map[x + " " + y]!}
   do Stuff
${map[x + " " + y]!}

2.Just convert that check into a true/false check. This could be done by using a utility class whith a isNull(Object obj) function.

utilClass.isNull(map[x + " " + y])==true

Upvotes: 1

Related Questions