You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Twig中按多键实现数组的分组与子分组?

在Twig中按主组+子组(subgroup)分层分组展示属性

你可以利用Twig内置的group过滤器实现需求,在原有主组遍历的基础上,对每组内的属性按subgroup字段二次分组。修改后的模板代码如下:

{% for attribute_group in attribute_groups %}
This is group: {{ attribute_group.name }}

    {% set grouped_attributes = attribute_group.attribute|group('subgroup') %}
    {% for subgroup_name, attributes in grouped_attributes %}
    --- Subgroup: {{ subgroup_name }} ---
        {% for attribute in attributes %}
        Attribute {{ attribute.name }} has value: {{ attribute.value }}
        {% endfor %}
    {% endfor %}

{% endfor %}

代码说明

  • attribute_group.attribute|group('subgroup'):将当前主组下的属性数组按subgroup字段分组,生成一个以子组名为键、对应属性集合为值的关联数组
  • 嵌套遍历分组后的结果:先输出子组名称,再遍历展示该子组下的所有属性

预期输出

This is group: Atribute Group #1

    --- Subgroup: SubGroup A ---
        Attribute Attrib1 has value: Val1
        Attribute Attrib3 has value: Val3
    --- Subgroup: SubGroup B ---
        Attribute Attrib2 has value: Val2
        Attribute Attrib4 has value: Val4

This is group: Atribute Group #2

    --- Subgroup: SubGroup A ---
        Attribute Attrib5 has value: Val5
        Attribute Attrib7 has value: Val7
    --- Subgroup: SubGroup C ---
        Attribute Attrib6 has value: Val6
        Attribute Attrib8 has value: Val8

可选优化:子组排序

如果需要子组按名称排序,可在分组后添加sort过滤器:

{% set grouped_attributes = attribute_group.attribute|group('subgroup')|sort %}

内容的提问来源于stack exchange,提问作者Bogdan Webb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 22:20:40