Fields should support twig iterable

Created on 10 August 2015, almost 10 years ago
Updated 26 May 2025, 8 days ago

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.

✨ Feature request
Status

Postponed: needs info

Version

11.0 πŸ”₯

Component

field system

Created by

πŸ‡ΊπŸ‡ΈUnited States tannerjfco

Live updates comments and jobs are added and updated live.
  • stale-issue-cleanup

    To track issues in the developing policy for closing stale issues, [Policy, no patch] closing older issues

Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡ΊπŸ‡ΈUnited States smustgrave

    Thank you for sharing your idea for improving Drupal.

    We are working to decide if this proposal meets the Criteria for evaluating proposed changes. There hasn't been any discussion here for over 8 years which suggests that this has either been implemented or there is no community support. Your thoughts on this will allow a decision to be made.

    Since we need more information to move forward with this issue, the status is now Postponed (maintainer needs more info). If we don't receive additional information to help with the issue, it may be closed after three months.

    Thanks!

Production build 0.71.5 2024