Score:0

Theming image.html.twig for one paragraph type with custom template suggestion

mz flag

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?

Score:0
cn flag

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

Droopaluser69 avatar
mz flag
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.
4uk4 avatar
cn flag
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.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.