【发布时间】:2013-07-15 22:54:30
【问题描述】:
我正在计算我在 Twig 中的数组中的条目数。这是我尝试过的代码:
{%for nc in notcount%}
{{ nc|length }}
{%endfor%}
然而,这只会产生数组中某个值的字符串的长度。
{{nc}} 将生成数组所有值的输出(有 2 个),但我希望输出只是数字 2(计数)而不是数组中的所有信息。
【问题讨论】:
标签: twig
我正在计算我在 Twig 中的数组中的条目数。这是我尝试过的代码:
{%for nc in notcount%}
{{ nc|length }}
{%endfor%}
然而,这只会产生数组中某个值的字符串的长度。
{{nc}} 将生成数组所有值的输出(有 2 个),但我希望输出只是数字 2(计数)而不是数组中的所有信息。
【问题讨论】:
标签: twig
只需在整个阵列上使用length filter。它不仅仅适用于字符串:
{{ notcount|length }}
【讨论】:
notcount不是数组,而是实现SPL Countable接口的类的对象(例如Doctrine的\Doctrine\Common\Collections\ArrayCollection就是这种情况),可以使用{{ notcount.count }}
获取长度的最佳实践是使用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 }}
有用的链接:
【讨论】:
这扩展了 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 %}
【讨论】: