Search code examples
twig

how to get only the number for how many certain keys (starts with) there are in a twig


I'm struggling to find a way to count certain keys in an array so I don't need to type all the keys in a computed_twig element for some calculations. I'm trying to get how many keys (questions) in the form so I can use the number in another step.

Questions are keys and each starts with q_. In this example there are 5 questions (q_1 to q_5). Here is a sample of my form (actual form has many groups of such questions with tens of questions, all starting with q_ then a sequential number e.g. q_1 ,... q_32 etc). I'm trialing in this twigfiddle

This is a minimal sample of my 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

First, I tried this but it returns all the correct keys while I only want the number of how many they are (i.e. 5 in this example):

{% for qs in qp1.ps1|keys %}
    {% if qs starts with 'q_' %}
    {{ qs }} {# this returns q_1 q_2 q_3 q_4 q_5 #}
    {% endif %}
{% endfor %}

Second, this is giving me as many "3"s as there correctly are q_ keys as 33333 but this is not what I want and I don't understand where the 3 came from!

{% for qs in qp1.ps1|keys %}
    {% if qs starts with 'q_' %}
    {{ qs | length }} {# this returns 3 3 3 3 3 (number "3" 5 times !) #}
    {% endif %}
{% endfor %}

Solution

  • A more clean solution would be to use the filter filter:

    {{ qp1.ps1|filter((v,k) => k starts with 'q_')|length }}
    

    You can assign the filtered result to a variable if needed be as well, e.g.

    {% set questions = qp1.ps1|filter((v,k) => k starts with 'q_') %}
    {{ questions | length }}
    

    demo