If you are struggling to fetch and display the label of a list field in a Twig template in Drupal, you are not alone. Fortunately, there are several ways to accomplish this. In this post, we will explore some of the most effective methods to help you display the label of a list field in your Twig template.

Using Allowed Values

One of the easiest ways to fetch the label of a list field is by using the Allowed Values feature. This feature stores the list of allowed values in the field configuration. Here's how to use this feature to fetch and display the label of a list field:

When field cardinality is 1:

<div>
  {% set list_value = node.field_list.value %}
  {{ node.field_list.getSetting('allowed_values')[list_value] }}
</div>

When field cardinality is more than 1:

<div>
  {% set allowed_values = node.field_list.getSetting('allowed_values') %}
  {% set list_values = node.field_list.getValue() %}
  {% for list_value in list_values %}
    <div>
      {{ allowed_values[list_value['value']] }}
    </div>
  {% endfor %}
</div>

Using Field Formatters

Another way to fetch and display the label of a list field is by using field formatters. If your Twig template is node.html.twig, you can render the field based on the field formatter in your view mode. Here's an example of how to do this:

<div>
  {{ content.field_list }}
</div>

Using PHP

If you prefer to use PHP, you can fetch the label of a list field using the getSettings() method. Here's an example of how to use PHP to fetch the label of a list field:

private function getListTypeValue($node, $fieldName) {
  $listField = $node->get($fieldName);
  return $listField->getSettings()['allowed_values'][$listField->value] ?? '';
}

Using Twig Field Value

Finally, you can use the module Twig Field Value to help you display the label of a list field. Once installed, you can use the following code to display the label:

{{ content.field_list|field_label }}