2013-07-15 241 views
40

我正在計算我在Twig中的數組中的條目數。這是我試過的代碼:計算數組中元素的數量

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

但是這隻會產生數組中其中一個值的字符串長度。

{{nc}}將產生數組的所有值(有2個)的輸出,但我希望輸出只是數字2(計數)而不是數組中的所有信息。

回答

73

只需在整個陣列上使用length filter即可。它適用於多隻串:

{{ notcount|length }} 
+2

這是完美的。我感到很傻。哈哈非常感謝你! – MikeHolford

+2

@MikeHolford沒問題。我很高興能夠提供幫助 – Paulpro

1

獲得最佳長度的做法是使用length過濾器返回序列或映射,或者一個字符串的長度的項目數。例如:{{ notcount | length }}

但是,您可以計算for循環中元素的計數。例如:

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

{{ count }} 

該解決方案幫助,如果你要計算的條件要素的數量,例如,你有內部對象的屬性name,你要計算的對象的數量有沒有空的名字:

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

{{ countNotEmpty }} 

相關鏈接:

0

它擴展了由丹尼斯·布勃諾夫答案。

我用它來查找數組元素的子值 - 即如果在Drupal 8站點的段落中存在一個錨字段來構建目錄。

{% set count = 0 %} 
{% for anchor in items %} 
    {% if anchor.content['#paragraph'].field_anchor_link.0.value %} 
     {% set count = count + 1 %} 
    {% endif %} 
{% endfor %} 

{% if count > 0 %} 
--- build the toc here -- 
{% endif %}