Multivalue field with Twig and its length I am playing around with Twig and D8. I created a content type called community and it contains a field called field_banner_images which is an image field with a max limit of 10 images.

I am trying to get the length of field_banner_images via Twig, but the number I am receiving is incorrect. My current node has 10 images on it. It also has alt text enabled if that makes a difference.

I created a file called node--community.html.twig and inside I have: 

{{ content.field_banner_images|length }}

which outputs 26, which is wrong. I would expect it to output 10.

Furthermore, I add

{% for item in content.field_banner_images %}
  &lt;span class="banner-img"&gt;{{ content.field_banner_images[loop.index0] }}&lt;/span&gt;
{% endfor %}


and while it does output the 10 images wrapped in span elements, I also get 16 empty span elements since it is looping 26 times.

What am I doing wrong here?
How to count in page or node template

content is the render array of the fields, that is build according to the view mode you have configured. The render array contains a lot of additional elements, that are not field items.

If you want to count the items in the field that are in the database, use the node object:

In php:

$node-&gt;field_banner_images-&gt;count();


In twig:

count() is not on the whitelist of allowed methods. Use .getvalue() instead, which gets the complete field array and count the array keys with the filter length:

{{ node.field_banner_images.getvalue|length }}


Better solution with field template

But you don't have to code the loop yourself in the node template, you can add the wrapper in the field twig.

Put the complete field in the node template:

{{ content.field_banner_images }}


And then put the wrapper in:

field--field-banner-images.html.twig

{% for item in items %}
    &lt;span&gt;{{ item.content }}&lt;/span&gt;
{% endfor %}


You can remove the content of the field twig and replace it with the code above. You know the content of this field and you don't need the div containers, when you want span's.