Counting the number of elements in array

前端 未结 3 639
你的背包
你的背包 2021-02-03 16:56

I am looking to count the number of entries I have in an array in Twig. This is the code I\'ve tried:

{%for nc in notcount%}
{{ nc|length }}
{%endfor%}
         


        
3条回答
  •  一生所求
    2021-02-03 17:16

    Best practice of getting length is use length filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}

    But you can calculate count of elements in for loop. For example:

    {% set count = 0 %}
    {% for nc in notcount %}
        {% set count = count + 1 %}
    {% endfor %}
    
    {{ count }}
    

    This solution helps if you want to calculate count of elements by condition, for example you have a property name inside object and you want to calculate count of objects with not empty names:

    {% set countNotEmpty = 0 %}
    {% for nc in notcount if nc.name %}
        {% set countNotEmpty = countNotEmpty + 1 %}
    {% endfor %}
    
    {{ countNotEmpty }}
    

    Useful links:

    • length
    • set
    • for

提交回复
热议问题