如何在Freemarker中的Map中迭代嵌套集合?

时间:2017-04-03 14:45:10

标签: java freemarker

我想在Freemarker 2.3.15中的Map中遍历嵌套集合。

我将以下内容传递给视图:

Map<ApplicationPropertyDefinition, Collection<ApplicationProperty>> = getValues();

我尝试过以下方法:

<#if propertiesByDefinition?size gt 0>
<#list propertiesByDefinition?keys as definition>
    <strong>${definition.externalReference!''}</strong>

    <#list propertiesByDefinition?values as value>
        ${value.name}
    </#list>

</#list>
</#if>

错误:

Expected hash. value evaluated instead to freemarker.template.SimpleSequence on line 65, column 19 in templates/propertygroup/values.txt.
The problematic instruction:
----------
==> ${value.name} escaped ${(value.name!"")?html} [on line 65, column 17 in templates/propertygroup/values.txt]
----------

如何正确迭代嵌套的Collection,以便我可以访问String值&#34; name&#34;在每个ApplicationProperty对象中?

2 个答案:

答案 0 :(得分:1)

您必须为给定的Collection

检索definition个对象

试试这个:

<#if propertiesByDefinition?size gt 0>
    <#list propertiesByDefinition?keys as definition >
        <strong>${definition.externalReference!''}</strong>

        <#list propertiesByDefinition.get(definition) as value>
            ${value.name}
        </#list>

    </#list>
</#if>

这里有一些代码改进:

<#if propertiesByDefinition?has_content >
    <#list propertiesByDefinition as definition, collection >
        <strong>${definition.externalReference!''}</strong>

        <#list collection as value >
            ${value.name}
        </#list>

    </#list>
</#if>

此处我使用自Freemarker 2.3.25后可用地图的#list键值对...

<#list map as key, value>
    ${key} : ${value}
</#list>

答案 1 :(得分:0)

您可以尝试添加一个以ApplicationPropertyDefinition为参数的方法,并返回为该参数找到的集合。

public Collection<ApplicationProperty> getPropertiesForDefinition(ApplicationPropertyDefinition definition) {
    return propertiesByDefinition.get(definition)
}

哪会导致:

<#list propertiesByDefinition?keys as definition>
    <strong>${definition.externalReference!''}</strong>

    <#list getPropertiesByDefinition(definition) as value>
        ${value.name}
    </#list>
</#list>