Problem/Motivation
Twig has a feature to check if an object is iterable: http://twig.sensiolabs.org/doc/tests/iterable.html
This would be desirable in relation to fields that may accept multiple values. For example, I might want to write a template like this that would allow to display field items as a list when there are multiple values, but otherwise display a single field item as a div without the wrapper.
<div{{ attributes.addClass(classes) }}>
{% if not label_hidden %}
<h3{{ title_attributes.addClass(title_classes) }}>{{ label }}</h3>
{% endif %}
{% if items is iterable %}
<ul{{ content_attributes.addClass('field-items') }}>
{% for item in items %}
{{ kint() }}
<li{{ item.attributes.addClass('field-item') }}>{{ item.content }}</li>
{% endfor %}
</ul>
{% else %}
<div{{ item.attributes.addClass('field-item') }}>{{ item.content }}</div>
{% endif %}
</div>
I have tested this in the current beta release (8.0.0-beta14 at time of writing), and while adding this to the template causes no errors, it also does not produce the expected behavior. I suspect that would be because fields end up being iterable objects to twig regardless of how many values they have. I also suspect that being able to support this feature for fields would be non-trivial, so I'm adding it initially as a feature request for 8.1.x.
Comments