0

I have a custom module that when installed, creates a paragraph type called "Gallery". Gallery has one field called "field_gallery_images", which is a media reference.

I am trying to replace image.html.twig with image--gallery.html.twig only for images inside my gallery.

I have managed to get Drupal to recognise and load my custom template from the modules template directory. However, every single image on the site now uses this template. I only want the template to be used for images of my paragraph type (or it's field). All other images should use the default image.html.twig.

Here is gallery.module:

function gallery_theme($existing, $type, $theme, $path) {
  return [
        'image__gallery' => [
      'template' => 'image--gallery',
      'base hook' => 'image',
    ],
  ];
}

function gallery_theme_suggestions_image_alter(array &$suggestions, array $variables) {
 $suggestions[] = 'image__gallery';
}

There is nothing I can test against inside any of the variables passed into both hooks to target my templates scope.

Am I using the wrong hooks?

1 Answer 1

0

Yes, the variables passed by default are not very helpful. The trick is to add an identifier of the field to the image attributes in field preprocessing. See this great answer How to add attributes to a specific field's image

2
  • Thank you for pointing that out, helpful to know. I couldn't find a way access the image via hook_preprocess_field as images are nested inside media so I had to put a flag inside the media object, then use hook_preprocess_media to check for the flag and set an attribute which I could then test against inside hook_theme_suggestions_image_alter - not pretty but it works. Jun 27 at 8:59
  • You have to be careful with that, media can be re-used, To avoid that configure a separate media type only used in this media reference field. This media type could simply contain an image field with a unique name or, if you keep the standard name for media images, you can test in field preprocess the bundle name of the parent entity of the field against the media type name.
    – 4uk4
    Jun 27 at 9:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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