我想要计算我在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)
小智 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)
获取长度的最佳实践是使用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)
有用的链接:
| 归档时间: |
|
| 查看次数: |
83230 次 |
| 最近记录: |