首页 > 解决方案 > 如何在 FTL(Freemarker) 中创建地图列表

问题描述

我有一个列表地图,testMap里面的列表有一个地图列表testMap

testMap = {"list1": list1, "list2" : list2}

list1 = [{"key" : value, "key" : value1},{"key" : value, "key" : value1}]

list2 = [{"key" : value, "key" : value1},{"key" : value, "key" : value1}]

我想根据列表中键的值将 testMap 分成 2 个映射 testMap1 和 testMap2。

这是我尝试过的

<#assign testMap1 = {}>
<#assign testMap2 = {}>

<#list testMap?keys as key>
    <#assign testMapList = testMap[key]>
    <#assign testList1 = []>
    <#assign testList2 = []>
        <#list testMapList as testList>
            <#if actionMap["key1"]??>
                <#if actionMap["key1"] == "test">
                     <#assign ignore = testList1.add(testList)>
                <#elseif actionMap["key1"] == "test1>
                    <#assign ignore = testList2.add(testList)>
                </#if>
            </#if>
        </#list>

        <#if testList1?has_content>
             <#assign ignore = testMap1.put(key, testList1)>
        <#elseif testList2?has_content>
            <#assign ignore = testMap2.put(key, testList2)>
        </#if>

</#list>

但是 <#assign ignore = testList1.add(testList)>这条线抛出了一个错误

"FreeMarker 模板错误:对于 ""."" 左侧操作数:应为哈希,但这已评估为序列(包装器:ftSimpleSequence):

我不知道我怎样才能做到这一点。任何帮助,将不胜感激。

标签: javafreemarker

解决方案


模板语言不是为做这些事情而设计的。您应该将此因素考虑到您从模板中调用的 Java 实用程序中。或者,如果无论呈现(格式)如何,这种重组都是有意义的,则将数据放入已经像这样结构化的数据模型中。

但是......如果你真的必须在模板内做,并且testMap没有很多键:

<#assign testMap1 = {}>
<#assign testMap2 = {}>
<#list testMap as k, v>
  <#assign map1V = v?filter(it -> it.key1 == 1)>
  <#if map1V?size != 0>
    <#assign testMap1 = testMap1 + {k: map1V}>
  </#if>

  <#assign map2V = v?filter(it -> it.key1 != 1)>
  <#if map1V?size != 0>
    <#assign testMap2 = testMap2 + {k: map2V}>
  </#if>
</#list>

读取生成的两个映射会很O(N)慢,其中 N 是其中的顶级键的数量。这就是为什么那里没有很多钥匙很重要的原因。

在调用add/put时,通常是不可能的。一种解决方法是添加一个实用程序来创建 ArrayList的or LinkedHashMap,然后您可以使用myList?api.add(...)等。在那里,?api允许您访问 Java API。但同样不适用于使用[]or创建的值{};无论如何,这些都不是可变的集合。


推荐阅读