Drupal - Iterate through multiple value content field in Twig template
Agree with 4k4 the field template is the best place, if you really want it in the entity template (e.g. node) you can do something like this:
{% for key, item in content.field_tags if key|first != '#' %}
<div class="item-{{ key + 1 }}">{{ item }}</div>
{% endfor %}
But honestly I think it's a bit ugly, the field template is the right place.
You can fix this in a field twig. There you can use the existing loop to iterate over the field items:
node.html.twig
{{ content.field_admin_tags }}
field--field-admin-tags.html.twig
<ul{{ attributes }}>
{% for item in items %}
<li>{{ item.content }}</li>
{% endfor %}
</ul>
This example replaces <div>
with <ul>
. Don't remove {{ attributes }}
or bypass the field template, see What can break quickedit, and how do I fix it?
If you, like me, are looking for a way to iterate through paragraphs on a node's twig template, here is how to do it:
Suppose you have a node with a multivalued paragraph field, so a content editor can create multiple paragraphs and you wish to iterate through each paragraph on the nodes twig template (for example to add a wrapper around each paragraph):
{% for key,value in node.my_paragraph_field.value %}
{{ content.my_paragraph_field[key] }}
{% endfor %}
UPDATE: I needed to find another way to print all paragraphs without using content. The content variable contains everything you set up in the 'Manage display' section of the node, but my current work method is to never use 'Manage display' nor layouts since you can actually access all data in the node twig file, and almost all settings you would do on 'Manage display', like applying an image style, or setting a date format, ... you can do directly in twig.
For me this is an advantage because I know that everything I see comes from the twig file, and I do not need to look for some obscure field settings that may add classes somewhere. So everything I see comes from just one place (the nodes twig file) and not a combination of the twig file and the manage display screen.
Anyway, using the awesome Twig Tweak module, here is how to print a multi value paragraph field in a node's twig file without having to use the content variable:
{% for item in node.field_paragraphs %}
{{ drupal_entity('paragraph', item.target_id) }}
{% endfor %}