3

I'm looking for an option to override the image-formatter.html.twig template in my own theme. But in the HTML page output (twig debug is set to true) there's no option listed to override the formatter template. The only thing I see is:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'image_formatter' -->
<!-- BEGIN OUTPUT from 'core/modules/image/templates/image-formatter.html.twig' -->

I need to place a rel attribute for the link which surrounds the image.

I found a solution which uses the option that you can write your own field formatter in your own module. But that seems to be too complex for this simple task.

2
  • That debug output doesn't mean you can't override the template, it just means there are no additional/more specific template suggestions. You may be able to add your own suggestion to meet this use case. I can try to write up an answer showing how to do that if that sounds helpful but the granularity may be somewhat limited. For example within this context we probably don't know what the image field is called but we do know the image style. If you want to add rel to all image formatter output it's a simple template override.
    – star-szr
    Commented Nov 22, 2014 at 15:30
  • Thx for your comment. Yes that sounds helpful. I like to override the template for a specific node type and a specific field in those nodes. So I can use something like field-formatter--node--mynode--my-field.html.twig? Commented Nov 24, 2014 at 7:27

1 Answer 1

15

In your .theme file, add this suggestions alter hook (and flush caches so the new hook definition is picked up):

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_formatter_alter(array &$suggestions, array $variables) {
  $entity = $variables['item']->getEntity();
  $field_name = $variables['item']->getParent()->getName();
  $suggestions[] = 'image_formatter__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name;
}

Then if you look at the twig_debug output, you should see something like:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'image_formatter' -->
<!-- FILE NAME SUGGESTIONS:
   * image-formatter--node--article--field-image.html.twig
   x image-formatter.html.twig
-->

Once that is done, you can create your template file called image-formatter--node--article--field-image.html.twig in the templates directory of your theme, flush caches again so the template is picked up, and override the template with any changes you'd like.

This should include a caveat that the code hasn't been thoroughly tested :)

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.