首页 > 解决方案 > 在 Freemarker 模板中迭代 HashMap 会显示 map 的方法

问题描述

在 Apache OfBiz 应用程序中,我在控制器中有这样的代码:

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

在 freemarker 模板中,它的处理/迭代如下:

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

在呈现的 html 页面上,我得到了实际地图的字符串键和地图的方法名称(放置、删除、添加等)。

至于值,它们根本没有呈现,并出现以下错误:

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)

我正在使用freemarker 2.3.28

标签: freemarkerofbiz

解决方案


Map.entrySet() 方法返回Set<Map.Entry<K, V>>此映射中包含的映射的集合 ()。所以我们可以使用 Map.Entry 的 getKey() 和 getValue() 方法迭代键值对<K, V>。此方法最常见,如果您在循环中需要映射键和值,则应使用此方法。

尝试使用此代码遍历 FTL 中的值

<table>
  <#list requestAttributes.entrySet() as requestAttribute>
  <tr>
    <td>${requestAttribute.getKey()}</td>
    <td>${requestAttribute.getValue()}</td>
  </tr>
  </#list>
</table>

推荐阅读