twig - 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 %}
解决方案
如果您想让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 %}
推荐阅读
- jenkins - 在 Jenkins/Groovy 中替代 `list.findIndexOf`
- c++ - Mac 上的 VSCode 不接受输入,而是显示“cmdand cmdand quote>”
- angular - Angular 9 前端/springboot 后端 - 调用 router.navigate(url) 时如何解决 CORS 错误
- php - 我的数组只是在数据库中插入一次并忽略其他数据
- sqlite - 创建串联结果表
- vb.net - 在数据网格的单列上连接字符串
- charts - 烛台图上绘制的简单移动平均线的趋势分析
- javascript - 当列上有渲染时,getColumnSearchProps 不起作用
- node.js - GraphQL 模块 - 为除公共操作之外的所有操作运行中间件
- typescript - typescript 实例化类型定义