freemarker - 在 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
解决方案
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>
推荐阅读
- html - 替换 HTML 字符串
- ocaml - 优拓不响应
- c - 无法在 mergeSort 函数中释放内存
- javascript - SAP UI5:合并/连接两个表
- python - 为什么使用 BeautifulSoup find_all 方法会导致错误(列表索引超出范围)?
- javascript - 为什么 javascript 中的 switch case 不适用于 Microsoft Edge 上的字符串?
- selenium - 如果它不是输入标签,如何在 selenium 中的特定字段中输入值
- angular - 禁用输入组件时发出警告
- html - 删除空间/使用 Tampermonkey?
- javascript - jquery中的某些事件调用后如何自动单击我的textarea