如何在Twig中统计以q_开头的指定键的数量
在Twig中统计数组内指定前缀键的数量
问题需求
需要统计Webform数组中以q_开头的键的数量,无需手动枚举所有键。示例中有5个(q_1到q_5),实际场景中可能包含数十个此类键。
示例Webform YAML
qp1: '#type': wizard_page '#title': 'Part I' '#open': true ps1: '#type': details '#title': title... '#required': true '#attributes': class: - qp1_1 q_1: '#type': radios '#title': q1..... '#options': - 'option 1 with value 0' - 'option 2 with value 1' - 'option 3 with value 2' - 'option 4 with value 3' '#required': true q_2: '#type': radios '#title': q2.... '#options': - 'option 1 with value 0' - 'option 2 with value 1' - 'option 3 with value 2' - 'option 4 with value 3' '#required': true q_3: '#type': radios '#title': q3..... '#options': - 'option 1 with value 0' - 'option 2 with value 1' - 'option 3 with value 2' - 'option 4 with value 3' '#required': true q_4: '#type': radios '#title': q4....... '#options': - 'option 1 with value 0' - 'option 2 with value 1' - 'option 3 with value 2' - 'option 4 with value 3' '#required': true q_5: '#type': radios '#title': q5........ '#options': - 'option 1 with value 0' - 'option 2 with value 1' - 'option 3 with value 2' - 'option 4 with value 3' '#required': true
之前尝试的问题
- 第一段代码返回所有符合条件的键名,而非数量:
{% for qs in qp1.ps1|keys %} {% if qs starts with 'q_' %} {{ qs }} {# 返回 q_1 q_2 q_3 q_4 q_5 #} {% endif %} {% endfor %}
- 第二段代码返回每个键名的长度(比如
q_1的长度是3,所以输出5个3),不是总数量:
{% for qs in qp1.ps1|keys %} {% if qs starts with 'q_' %} {{ qs | length }} {# 返回 3 3 3 3 3 #} {% endif %} {% endfor %}
解决方案
方法1:使用计数器变量
初始化一个计数器,遍历过程中对符合条件的键进行计数,最后输出结果:
{% set count = 0 %} {% for qs in qp1.ps1|keys %} {% if qs starts with 'q_' %} {% set count = count + 1 %} {% endif %} {% endfor %} {{ count }} {# 输出 5 #}
方法2:链式过滤器(更简洁)
通过filter筛选出目标键,再用length直接统计数量:
{{ qp1.ps1|keys|filter(key => key starts with 'q_')|length }}
逻辑说明
keys过滤器:提取数组的所有键名filter过滤器:筛选出以q_开头的键length过滤器:统计筛选后数组的元素数量,即符合条件的键的总数
内容的提问来源于stack exchange,提问作者Adam888
相关产品推荐
相关产品推荐

