过滤带表达式的bean列表

Thi*_*ier 2 freemarker

我有一个bean列表,我希望得到一个子列表,其中一个或多个属性的条件与表达式匹配如下:

${data[propertyName=='my value']}
Run Code Online (Sandbox Code Playgroud)

data是具有名为propertyName的属性的bean列表.

这样的方法可能吗?如果没有,那么最好的办法是什么.

非常感谢您的回答.蒂埃里

Cha*_*tay 13

您可以编写一个FTL函数,该函数选择符合条件的列表项,并通过序列连接以新的顺序收集它们.您的过滤功能可以非常简单或非常复杂,具体取决于您的实际使用情况.以下是一个如何工作的示例:

<#function filter things name value>
    <#local result = []>
    <#list things as thing>
        <#if thing[name] == value>
            <#local result = result + [thing]>
        </#if>
    </#list>
    <#return result>
</#function>

<#-- some test data -->
<#assign data = [ {"propertyName":"my value",    "foo":150},
                  {"propertyName":"other value", "foo":250},
                  {"propertyName":"my value",    "foo":120}] >

<#assign filteredData = filter(data, "propertyName", "my value") >

<#list filteredData as item>
    ${item.foo}
</#list>
Run Code Online (Sandbox Code Playgroud)

但请注意,使用序列连接可能对您的性能"不是最理想的".