计算数组中的元素数量

Mik*_*ord 55 twig

我想要计算我在Twig中的数组中的条目数.这是我试过的代码:

{%for nc in notcount%}
{{ nc|length }}
{%endfor%}
Run Code Online (Sandbox Code Playgroud)

但是,这仅产生数组中某个值的字符串的长度.

{{nc}} 将产生数组的所有值的输出(有2)但我希望输出只是数字2(计数)而不是数组中的所有信息.

Pau*_*aul 111

只需在整个阵列上使用长度过滤器即可.它的工作原理不仅仅是字符串:

{{ notcount|length }}
Run Code Online (Sandbox Code Playgroud)

  • 那真是太完美了.我觉得很傻.哈哈,非常感谢你! (2认同)
  • @MikeHolford没问题.我很高兴我可以帮忙 (2认同)

小智 6

这扩展了丹尼斯·布布诺夫 (Denis Bubnov) 的回答。

我用它来查找数组元素的子值——也就是说,如果 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 %}
Run Code Online (Sandbox Code Playgroud)


Den*_*nov 5

获取长度的最佳实践是使用length过滤器返回序列或映射的项目数,或字符串的长度。例如:{{ notcount | length }}

但是您可以计算for循环中元素的数量。例如:

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

{{ count }}
Run Code Online (Sandbox Code Playgroud)

如果您想按条件计算元素的数量,例如您在name对象内部有一个属性,并且您想计算名称不为空的对象的数量,则此解决方案会有所帮助:

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

{{ countNotEmpty }}
Run Code Online (Sandbox Code Playgroud)

有用的链接: