Can I modify core/image twig template only for specified entity.field?

I want to modify img tag output only for commerce_product.images custom field but there is only 1 suggestion themes/bootstrap/templates/system/image.html.twig which override all image uses.

<div class="field--item">
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'image_formatter' -->
<!-- BEGIN OUTPUT from 'core/modules/image/templates/image-formatter.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'image' -->

<!-- BEGIN OUTPUT from 'themes/bootstrap/templates/system/image.html.twig' -->

<img src="zz.jpg" alt="alttext" typeof="foaf:Image" class="img-responsive" height="150" width="150">

<!-- END OUTPUT from 'themes/bootstrap/templates/system/image.html.twig' -->
<!-- END OUTPUT from 'core/modules/image/templates/image-formatter.html.twig' -->


EDIT1: if i'm implement hook_theme_suggestions_HOOK_alterm there is no entity or field info:

function mytheme_theme_suggestions_image_alter(array &$suggestions, array $variables) {
  $entity = $variables['item']->getEntity(); //ERROR
  • Can you clarify what exactly you want to do with the image tag? Just add class/attribute? Might not be so complicated after all. Also, it looks like you use the original image. I'd recommend to always use an image style, unless you have full control over the exact size of he original images.
    – Berdir
    Feb 24, 2016 at 19:19

2 Answers 2


It's possible but very difficult to do.

You would have to alter to output of the image formatter to inject a theme suggestion on the image_formatter template (or create your own image formatter).

Then you would need to inject the suggestion from the formatter to the image theme function (could be done in a preprocess).

The issue is that altering the output would probably be something you would handle in each unique case, so you would basically need to create your own image formatter.

It's not a lot of work, but a bit tricky.

TL:DR; Yes it's possible but you don't want to do that.


As Berdir says, you can do this easily if you use an image style specific to your field/need.

function THEMENAME_theme_suggestions_image_alter(array &$suggestions, array $variables) {
  $suggestions[] = 'image__' . $variables['style_name'];

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.