3

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?

  • What is the filename for the first template? – kiamlaluno Aug 29 '15 at 13:36
  • @kiamlaluno field-image.html.twig, but I'm overriding the template from my custom field formatter, not a theme. – Mad Scientist Aug 29 '15 at 13:39
4

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.

1

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.

  • 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 '15 at 15:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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