more logical field.html.twig

Created on 6 February 2019, almost 6 years ago
Updated 21 January 2023, almost 2 years ago

(I’m a new Drupal contributor; this is my first issue submission.)

Problem

The default Field file (/web/core/themes/stable/templates/field/field.html.twig) is a bit clumsy—the "if-else tree" contains a lot of duplicates, so overriding this file, e.g., forking it into your own theme and modifying it, is a slightly tedious process. For example, the <div{{ item.attributes }}>{{ item.content }}</div> element appears 3 times unnecessarily.

Suggested Solution

I went in and streamlined the cases in the logic tree, so the file is much easier to read, understand, and override.

My request is to change the file contents as shown below. A diff file is attached.

Old code

{%
  set title_classes = [
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

{% if label_hidden %}
  {% if multiple %}
    <div{{ attributes }}>
      {% for item in items %}
        <div{{ item.attributes }}>{{ item.content }}</div>
      {% endfor %}
    </div>
  {% else %}
    {% for item in items %}
      <div{{ attributes }}>{{ item.content }}</div>
    {% endfor %}
  {% endif %}
{% else %}
  <div{{ attributes }}>
    <div{{ title_attributes.addClass(title_classes) }}>{{ label }}</div>
    {% if multiple %}
      <div>
    {% endif %}
    {% for item in items %}
      <div{{ item.attributes }}>{{ item.content }}</div>
    {% endfor %}
    {% if multiple %}
      </div>
    {% endif %}
  </div>
{% endif %}

New (suggested) code

{%
  set title_classes = [
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}
<div{{ attributes }}>
  {% if not label_hidden %}
    <div{{ title_attributes.addClass(title_classes) }}>{{ label }}</div>
  {% endif %}
  {% if multiple %}
    <div>
  {% endif %}
  {% for item in items %}
    <div{{ item.attributes }}>{{ item.content }}</div>
  {% endfor %}
  {% if multiple %}
    </div>
  {% endif %}
</div>
Feature request
Status

Needs work

Version

9.5

Component
Field 

Last updated 5 days ago

Created by

🇺🇸United States chharvey

Live updates comments and jobs are added and updated live.
  • Needs frontend framework manager review

    Used to alert the fron-tend framework manager core committer(s) that a front-end focused issue significantly impacts (or has the potential to impact) multiple subsystems or represents a significant change or addition in architecture or public APIs, and their signoff is needed (see the governance policy for more information). If an issue significantly impacts only one subsystem, use Needs subsystem maintainer review instead, and make sure the issue component is set to the correct subsystem.

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.

No activities found.

Production build 0.71.5 2024