4

I have a custom field formatter for an image field. The Twig template for the image field is the following:

{% for item in items %}
  {{ item.content }}
{% endfor %}

Each image is then formatted by the following template:

<li data-src={{ fullimage }}><img src="{{ thumbnail }}" /></li>

But what I want to do is to format the first image of the field in a different way. I found how I could change the for loop in the template and use loop.first to treat the first image differently. But the formatting I want to change is in the inner template that formats each image, the one I call with item.content. In the outer template for the entire image field I can distinguish the first image, in the inner template I have no idea how to check for that or how to transfer that information from the outer to the inner template.

Any idea on how I can solve this and format only the first image in a different way?

3
  • What is the filename for the first template?
    – apaderno
    Aug 29, 2015 at 13:36
  • @kiamlaluno field-image.html.twig, but I'm overriding the template from my custom field formatter, not a theme. Aug 29, 2015 at 13:39
  • Sounds like you should implement a custom field formatter. Just copy the default from core over to a custom module, rename everything properly and then jump in to the foreach that there is. Similar to what's been done here: drupal.stackexchange.com/a/171471/15055
    – leymannx
    Jan 13, 2021 at 20:44

2 Answers 2

5

This code in a node.html.twig template will display only the first value of an image field that has multiple values:

{{ content.field_yourfieldname.0 }}

This will only display the second value:

{{ content.field_yourfieldname.1 }}

Source

Edit: apparently that wasn't really the question, my apologies.

0
0

What you want to do, is to add a suggestion for the image field, based of the delta value of the field item.

Drupal has extensive documentation on working with suggestions in Drupal 8.

1
  • Thanks, could you elaborate about the "delta value" of the field ? What is it and did they contain the index of the current iterated item ?
    – GiDo
    Oct 1, 2015 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.