drupaltwigdrupal-8drupal-templates

Unique id to recurring field in twig - Drupal 8


I have a Drupal content type that uses multiple referenced entities of the same type (say, "related products")

I want to give the title field of every related product a unique ID. It can be the product name, an iterator, the ID of the product's node, whichever is easiest.

I created a twig template that overrides the title of said node in said content type: field--node--title--my-content-type.html.twig but I have no idea where to go from here.

I can add a custom id with

{% set attributes = attributes.setAttribute('id', 'customID') %}

but that's static, and would not be unique when the field is called multiple times.

{% set node = element['#object'] %} and {{ item.content['#node'].field_name.value }} as recommended here don't work for me.

If possible, I want to solve it twig-only, without any additional php code.

any pointers or suggestions are much appreciated


Solution

  • You can modify the code that loops through the items array.

    For example, I added an iteration index:

    field--node--title--my-content-type.html.twig

    {# Here I coppied template from web/core/modules/system/templates/field.html.twig and modified it #}
    {%
      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 index, item in items %}                                     {# use index #}
            <span>{{ index }}</span>                                         {# and print it #}
            <div{{ item.attributes }}>{{ item.content }}</div>
          {% endfor %}
          {% if multiple %}
        </div>
        {% endif %}
      </div>
    {% endif %}
    
    

    Result:

    enter image description here