首页 > 解决方案 > Craft/Twig 如何循环多个键/值对并从该循环中删除重复项?

问题描述

在 Craft CMS 中,我有子条目,其中每个子条目都有一个分配有“城市”和“国家”值的位置。

我正在寻找输出“城市,国家”文本的列表,但删除任何重复项,因为两个或多个孩子可能共享相同的“城市,国家”对。

重要的是,我可以分别引用每个子项的城市和国家/地区值,因为我需要使用国家/地区值来为列表中的每个子项显示标志。

我已经了解并尝试了“twig hash”和“associative arrays”,并找到了可用的片段,但无法使其适用于我的案例。

这不起作用:

{% set children = entry.children %}

{% set locations = {} %}

{% for child in children %}
    {% set city = child.location.parts.locality %}
    {% set country = child.location.parts.country %}

    {% if city not in locations %}
        {% set locations = locations|merge({ city : country }) %}
    {% endif %}

{% endfor %}

{% for location in locations %}
    {% for k, v in location %}
        {{ k }}, {{ v }} <br />
    {% endfor %}
{% endfor %}

标签: twigcraftcms

解决方案


如果您想让city成为数组的键,则需要将它们包装在括号中,以便变量由twig.

你也不需要双for循环,你正在构建一个一维数组

{% set locations = {} %}

{% for child in children %}
    {% set city = child.city %}
    {% set country = child.country %}

    {% if city not in locations %}
        {% set locations = locations|merge({ (city) : country }) %}
    {% endif %}

{% endfor %}

{% for k,v in locations %}
    {{ k }}, {{ v }} <br />
{% endfor %}

演示


推荐阅读