Here's a modification of https://drupal.stackexchange.com/a/236408/67965 that loops through the render children instead of the field #items
.
The twig extension:
/**
* Generates a list of all Twig filters that this extension defines.
*/
public function getFilters() {
return [
new \Twig_SimpleFilter('children', array($this, 'children')),
];
}
/**
* Get the render children of a field
*/
public static function children($variable) {
return array_filter(
$variable,
function($k) { return (is_numeric($k) || (strpos($k, '#') !== 0)); },
ARRAY_FILTER_USE_KEY
);
}
In twig, you can then pass through rendered children directly, which helps in atomic design patterns. Define an entity template, for instance:
{% include '@molecules/grid.html.twig' with {
head : content.field_title,
grid_columns: content.field_collection_items|children
} %}
where grid.html.twig is something like:
{% if head %}
<div class="slab__wrapper">
{{ head }}
</div>
{% endif %}
<div class="grid">
{% for col in grid_columns %}
<div class="grid__column">
{{ col }}
</div>
{% endfor %}
</div>
This is usually more useful than having to render a field template for {{ content.field_collection_items }}
because the layout of the children may be controlled in the context of the parent design element.