【问题标题】:Freemarker: find one result in array of objectsFreemarker:在对象数组中找到一个结果
【发布时间】:2015-11-19 14:16:59
【问题描述】:

我有如下数组:

<#assign services = [
{'id': '1', 'name': 'AAAA'},
{'id': '22', 'name': 'BBBB'}
]>

我知道 id .. 例如 22。我需要这样的东西:

${services[2].name} // print BBBB

我试过了,但没有结果

${services[services.type?seq_index_of(22)].name}

有什么办法吗?

感谢您的帮助

【问题讨论】:

    标签: arrays multidimensional-array freemarker template-engine


    【解决方案1】:

    如果可以,请将服务模型作为映射而不是数组传递。否则,您可以遍历服务以找到正确的服务。如果您需要多次使用它,那么您可以将逻辑抽象成这样的宏:

    <#macro getServiceName id serviceList>
        <#list serviceList as service>
            <#if service['id']==id>
                ${service['name']}
                <#break/>
            </#if>
        </#list>
    </#macro>
    
    <#assign services = [
        {'id': '1', 'name': 'AAAA'},
        {'id': '22', 'name': 'BBBB'}
    ]>
    
    
    <#assign serviceId="22"/>
    service ${serviceId} name = <@getServiceName id=serviceId serviceList=services/>
    

    【讨论】:

    • 谢谢...宏是个好主意,我喜欢...我是freemarker的菜鸟
    【解决方案2】:

    您可以在services 数组上循环。

    <#assign services = [
    {'id': '1', 'name': 'AAAA'},
    {'id': '2', 'name': 'BBBB'},
    {'id': '22', 'name': 'CCCC'},
    {'id': '23', 'name': 'DDDD'}
    ]>
    
    <#list services as service>
       <#if service.id == '22'>
            Result: ${service.name}
        </#if>
    </#list>
    

    【讨论】:

    • 谢谢你的帮助,但我现在有这个解决方案,但我问我是否可以做得更好
    猜你喜欢
    • 2015-04-27
    • 2021-11-04
    • 2017-04-10
    • 1970-01-01
    • 2019-12-16
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    相关资源
    最近更新 更多