【发布时间】:2019-01-10 04:53:28
【问题描述】:
我有一个名为 lookup 的 HashMap<Integer, String>,它由我想在 Freemarker 模板中呈现的对象提供。
这是 Java 类:
public class SearchResultContainer implements Container<T> {
private final Map<Integer, String> lookup;
private final List<T> items;
public SearchResultContainer(List<T> items, Map<Integer, String> lookup) {
this.lookup= lookup;
this.items = items;
}
@Override
public List<T> getItems() {
return items;
}
public Map<Integer, String> getLookup() {
return this.lookup;
}
}
我尝试像这样访问地图的值:
<#-- @ftlvariable name="self" type="SearchResultContainer" -->
<#assign lookup=self.lookup/>
<#if lookup?has_content>
<#list lookup?keys as key>
${key} = ${lookup[key])}
</#list>
<#/if>
我得到这个错误:
对于 "...[...]" 左侧操作数:需要一个序列或字符串或自动转换为字符串(数字、日期或布尔值)的东西,但这已评估为扩展哈希(HashMap 包装到 ft DefaultMapAdapter):
==> 查找 [在模板中 [...]
[...]
提示:您在 [] 中有一个数字值。目前仅支持序列(列表)和字符串。要使用非字符串键获取地图项,请使用 myMap?api.get(myKey)。
[...]
然后我尝试按照建议使用?api:
<#list lookup?keys as key>
${key} = ${lookup?api.get(key)}
</#list>
我得到这个错误:
无法使用 ?api,因为“api_builtin_enabled”配置设置为 false。不过,在将其设置为 true 之前请三思。特别是,它不应该被滥用于修改 Map-s 和 Collection-s。
被指责的表情:
==> 查找?api [在模板中 [...]
除了在我的SearchResultContainer 类中提供额外的方法或启用api_builtin_enabled(不建议这样做)之外,还有其他方法可以访问地图吗?
【问题讨论】:
标签: java freemarker