Search code examples
freemarkerofbiz

Iterating over HashMap in Freemarker template displays map's methods


In Apache OfBiz application, I have such code in controller:

   public static String runRequest(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Long> typesToCount = getTypesToCount();
        request.setAttribute("types", typesToCount);
        return HttpFinals.RETURN_SUCCESS;
   }

And in freemarker template it's processed/iterated like so:

<table
<#list requestAttributes.types as key, value>
    <tr>
        <td>${key}</td>
        <td>${value}</td>
    </tr>
</#list>
</table>

On rendered html page I'm getting both actual map's string key's and map's methods names (put, remove, add etc.).

As for values they are not rendered at all the with following error:

FreeMarker template error: For "${...}" content: Expected a string or something automatically convertible to string (number, date or boolean), or "template output" , but this has evaluated to a method+sequence (wrapper: f.e.b.SimpleMethodModel)

I'm using freemarker 2.3.28


Solution

  • Basically, I managed to iterate through the map only after wrapping it in SimpleMapModel like so:

       public static String runRequest(HttpServletRequest request, HttpServletResponse response) {
           Map<String, Long> typesToCount = getTypesToCount();
           request.setAttribute("types",  new SimpleMapModel(typesToCount, new DefaultObjectWrapper())));
           return HttpFinals.RETURN_SUCCESS;
        }
    

    and int ftl template:

       <#list requestAttributes.types?keys as key>
       <tr>
           <td>${key}</td>
           <td>${requestAttributes.types[key]}</td>
       </tr>
       </#list>