How to add a class to the image tag The input in file field.html.twig is normally like this:

{% for item in items %}
&lt;div{{ attributes }}&gt;{{ item.content }}&lt;/div&gt;
{% endfor %}


And you get the output in HTML like this:

&lt;div&gt;&lt;img src="path/to/image/image.png" alt="my wonderful image"&gt;&lt;/div&gt;


But I want to add a class to img-tag. How do I receive the following output:

&lt;div&gt;&lt;img class="img-fluid" src="path/to/image/image.png" alt="my wonderful image"&gt;&lt;/div&gt;


I am looking for a solution like this (solution in another post), but it is not working. Can anybody help?
I'd prefer to avoid editing templates for such simple things as adding just classes. I'd recommend to edit templates only if you really need to make changes to the markup.

For adding a simple class to your image all you need is the following snippet placed in your custom (sub-)theme's *.theme file. (Replace MYTHEME with the actual machine name of your theme). This one identifies the image by its image style (so ensure to have an unique image style applied to your image):

/**
 * Implements template_preprocess_image().
 */
function MYTHEME_preprocess_image(&amp;$variables) {

  // Check the image style.
  if ($variables['style_name'] == 'img_fluid') {

    // Set class.
    $variables['attributes']['class'][] = 'img-fluid';
  }
}


If you are fine with adding the class not to the img tag directly, but to its wrapping container you could also use the following snippet. You can broaden the if-request as you like to only fire on certain content types (as you maybe use the same field in other content types as well), p.e. check for $variables['element']['#object']-&gt;bundle(). Replace field_MYIMAGE with your actual field name.

/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&amp;$variables) {

  // Check for your image field.
  if ($variables['element']['#field_name'] == 'field_MYIMAGE') {

    // Set class.
    $variables['attributes']['class'][] = 'img-fluid';
  }
}