开发者

Filtering list of beans with expression

I have a list of beans and I would like to get a sub list matching a criteria on one or several properties with an expression as below:

${data[propertyName=='my value']}

data is a list of beans that have a property called propertyName.

Is such appro开发者_Python百科ach possible? If not, what is the best approach to do that.

Thanks very much for your answers. Thierry


You could write a FTL function which selects the list items that match your criteria and collect them in a new sequence via sequence concatenation. Your filter function can be very simple or very sophisticated, it depends on your actual use case. Here is an example how it might work:

<#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>

But keep into account that using sequence concatenation might be "suboptimal" for your performance.


You could do it by creating your own filter method variable and exposing it to the template. Then it would just be a matter of calling it with the list of beans and property value you want to filter on:

<#assign filteredData = filter(data, "my value") />
<#list filteredData as item>
    // do something fancy
</#list>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜