Check if a map contains a specific key in Freemarker

Steve McLeod picture Steve McLeod · Nov 23, 2016 · Viewed 7k times · Source

In Java:

Map<String, Object> model = new HashMap<>();
Map<String, String> items = new HashMap<>();
items.put("color", "red");
model.put("items", items);

I now want to include a snippet in my rendered template if items contains the key color.

<#if ???? >
   the map contains a key called color
</#if>

What do I replace the ???? with?

Answer

glw picture glw · Nov 23, 2016

You can use ?? operator like this:

<#if items['color']?? >
   the map contains a key called color
</#if>