4

I'm trying to change the output of an image field so that I can display it using a Javascript image gallery. I have the basic field formatter set up, but I'm having trouble finding the correct place to override the theme that displays the <img> tag itself.

I'm overriding the viewElements function of the core ImageFormatter:

class ImageGalleryFormatter extends ImageFormatter { /** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items) { $elements = parent::viewElements($items); foreach ($elements as &$element) { $element['#theme'] = 'imagegallery_format'; } $elements['#attached']['library'][] = 'imagegallery_formatter/light-gallery'; return $elements; } } 

There I can set my custom Twig theme for each element, but that theme only writes the stuff directly around the <img> tag, not the tag itself. The theme provides access to an {{ image }} variable that renders the actual image. I tried accessing the variables inside the image like {{ image.uri }}, but that didn't work. I know the information I need is in there as I dumped the image variable in Twig and can see the array, but I can't access it from here.

From the Twig debug output I know that 'core/themes/classy/templates/field/image.html.twig' is the theme I need to override, but I can't find a way to do that from my module. I read the source of the core ImageFormatter viewElements function, but I don't see the image variable there and don't understand how I can modify it.

How can I override the theme that renders the <img> tag of an image field in my field formatter?

1
  • api.drupal.org/api/drupal/… here I can see tag . U need to create templates subfolder in module folder and put there appropriate twig file. Commented Aug 15, 2015 at 16:51

1 Answer 1

4

I'm no expert on field formatters in D8, but are you opposed to using a preprocessor? If not, have a look at template_preprocess_image_formatter. It looks like that is where you would prepare your own variables for use in the image formatter template. Cheers -

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.