我有以下代码 -
public class Result {
private Map<String, String> dataPoints = new LinkedHashMap<String, String>();
public Map<String, String> getData() {
return Maps.newHashMap(data);
}
public Set<Map.Entry<String, String>> getDataEntries() {
return data.entrySet();
}
public void addData(final String key, final String value) {
this.data.put(key, value);
}
}
我正在使用LinkedHashMap,因为我想维护插入顺序。我试图在我的freemarker代码中迭代地图,如下所示。但是,我得到了例外。
<#if (result.dataPoints?keys?size > 0) >
<#list result.getDataEntries() as entry>
<tr>
<td width="35%">
<div>${entry.key}</div>
</td>
<td width="45%">${entry.value}</td>
<td width="19%"> </td>
</tr>
</#list>
</#if>
例外:
Expression result.getDataEntries is undefined on line 50, column 24 in settings/settings-
diagnostics.ftl. The problematic instruction: ---------- ==> list result.getDataEntries()
as entry [on line 50, column 17 in settings/settings-diagnostics.ftl] in user-directive
printDiagnosticResult [on line 64, column 25 in settings/settings-diagnostics.ftl] in
user-directive printDiagnosticResult [on line 76, column 13 in settings/settings-
diagnostics.ftl] in user-directive layout.landingbase [on line 1, column 1 in
settings/settings-diagnostics.ftl] ---------- Java backtrace for programmers: ----------
freemarker.core.InvalidReferenceException: Expression result.getDataEntries is undefined
on line 50, column 24 in settings/settings-diagnostics.ftl. at
freemarker.core.TemplateObject.assertNonNull(TemplateObject.java:124) at
freemarker.core.TemplateObject.invalidTypeException(TemplateObject.java:134) at
freemarker.core.MethodCall._getAsTemplateModel(MethodCall.java:114) at
freemarker.core.Expression.getAsTemplateModel(Expression.java:89) at
freemarker.core.IteratorBlock.accept(IteratorBlock.java:94) at
freemarker.core.Environment.visit(Environment.java:208) at
如果我将以上代码替换为:
<#if (result.dataPoints?keys?size > 0) >
<#list result.dataPoints?keys as key>
<tr>
<td width="35%">
<div>${key}</div>
</td>
<td width="45%">${result.dataPoints[key]}</td>
<td width="19%"> </td>
</tr>
</#list>
</#if>
我知道如何迭代地图以便获得相同的订单?
答案 0 :(得分:2)
这应该可以解决问题:
<#if result.dataPoints?has_content >
<#list result.dataPoints.entrySet() as entry>
<tr>
<td width="35%">
<div>${entry.key}</div>
</td>
<td width="45%">${entry.value}</td>
<td width="19%"> </td>
</tr>
</#list>
</#if>
您可能还需要为freemarker
模板配置设置对象包装器。像这样:
BeansWrapper beansWrapper = (BeansWrapper) ObjectWrapper.BEANS_WRAPPER;
beansWrapper.setExposeFields(true);
config.setObjectWrapper(beansWrapper);
config
为freemarker.template.Configuration
的位置。
如果您使用Spring Framework,则扩展FreeMarkerConfigurer
:
public class FreeMarkerBeanWrapperConfigurer extends FreeMarkerConfigurer {
@Override
protected void postProcessConfiguration(Configuration config) throws IOException, TemplateException {
super.postProcessConfiguration(config);
BeansWrapper beansWrapper = (BeansWrapper) ObjectWrapper.BEANS_WRAPPER;
beansWrapper.setExposeFields(true);
config.setObjectWrapper(beansWrapper);
}
}