split field elements in 'prefix', 'content' and 'suffix'

Created on 9 February 2024, over 1 year ago

Problem/Motivation

For theming purpose, I'd like to split field elements in 'prefix', 'content' and 'suffix' and then display them in 3 different tags.
Is it possible with the Tiwg Tweak module?

Feature request
Status

Active

Version

3.2

Component

Code

Created by

🇫🇷France webmestre

Live updates comments and jobs are added and updated live.
  • theming

    Used in Documentation issues related to theming

Sign in to follow issues

Comments & Activities

  • Issue created by @webmestre
  • 🇫🇷France webmestre

    Here's a field template that makes the job:

    
    {%
      set classes = [
        'field',
        'field--name-' ~ field_name|clean_class,
        'field--type-' ~ field_type|clean_class,
        'field--label-' ~ label_display,
      ]
    %}
    {%
      set title_classes = [
        'field__label',
        label_display == 'visually_hidden' ? 'visually-hidden' : '',
      ]
    %}
    
    {# get prefix and suffix #}
    {% set prefix = element['#items'].getFieldDefinition().getSetting('prefix') ?? '' %}
    {% set suffix = element['#items'].getFieldDefinition().getSetting('suffix') ?? '' %}
    
    {# display the field #}
    <div{{ attributes.addClass(classes) }}>
      <div{{ title_attributes.addClass(title_classes) }}>{{ element['#title'] }}</div>
      {% if multiple %}
        <div class='field__items'>
      {% endif %}
      {% for item in items %}
        <span>{{ prefix }} </span>
        <span{{ item.attributes.addClass('field__item') }}>{{ item.content }}</span>
        <span> {{ suffix }}</span>
      {% endfor %}
      {% if multiple %}
        </div>
      {% endif %}
    </div>
    
    
  • Status changed to Closed: duplicate over 1 year ago
  • 🇷🇺Russia Chi

    The use case is kind of narrow. Only a few field types have support for prefix and suffix. Anyway I think it's a case for Twig Field Value module as it seems more related to processing field values.

    I guess it could be filters like this.

    {{ content.field_name|field_prefix }}
    {{ content.field_name|field_suffix }}
    
  • 🇩🇰Denmark ressa Copenhagen

    I was looking for a method to separate a field's content, suffix and prefix values, to be able to translate suffixes, so thank you very much for sharing a method @webmestre!

    Just to clarify to others finding this issue, there is no need for any extra Twig module to get separate content, suffix and prefix values. Just adds this in for example field.html.twig file (tested in Bootstrap5 ):

    {# get prefix and suffix #}
    {% set prefix = element['#items'].getFieldDefinition().getSetting('prefix') ?? '' %}
    {% set suffix = element['#items'].getFieldDefinition().getSetting('suffix') ?? '' %}
    

    ... and you can use the prefix and suffix elements like this:
    {{ suffix|trans }}

Production build 0.71.5 2024