Drupal - Loop through child elements in Twig like Element::children()
{% for key, child in element if key|first != '#' %}
<div>{{ child }}</div>
{% endfor %}
I have created a Twig filter that returns back with the children as an ArrayIterator
.
mymodule/mymodule.services.yml
services:
mymodule.twig_extension:
arguments: ['@renderer']
class: Drupal\mymodule\TwigExtension\Children
tags:
- { name: twig.extension }
mymodule/src/TwigExtension/Children.php
<?php
namespace Drupal\mymodule\TwigExtension;
class Children extends \Twig_Extension
{
/**
* Generates a list of all Twig filters that this extension defines.
*/
public function getFilters()
{
return [
new \Twig_SimpleFilter('children', array($this, 'children')),
];
}
/**
* Gets a unique identifier for this Twig extension.
*/
public function getName()
{
return 'mymodule.twig_extension';
}
/**
* Get the children of a field (FieldItemList)
*/
public static function Children($variable)
{
if (!empty($variable['#items'])
&& $variable['#items']->count() > 0
) {
return $variable['#items']->getIterator();
}
return null;
}
}
in the Twig template:
{% for headline in entity.field_headline|children %}
{{ headline.get('value').getValue() }}
{% endfor %}
Use the Twig Tweak module, which, among other wonderful features, has a "children" filter:
{% for item in content.field_name | children(true) %}
{# loop.length, loop.revindex, loop.revindex0, and loop.last are now available #}
{% endfor %}