0

For example, I want to override image template (image.html.twig) to change how it outputs images from

<img{{ attributes }} />

to

<div class="image" style="background-image: url('{{ attributes.src }}');"></div>

But I require to override only those images, that are rendered inside specific block type (called "bundle" in Drupal terms) b_partner_images.

There is a hook_theme_suggestions_alter(array &$suggestions, array $variables, $hook) hook, that allows to create suggestions based on some conditions, but the problem is that $variables does not contain anything more than image tag attributes - no objects or identifiers, so I see no way to create condition based on some identifiers or block (bundle) name.

How to create file name suggestion for system templates (such as image) to override image output based on block type or any other identifier?

0

Currently, I have only found a workaround using image-formatter override

Create a file name suggestion hook for theme in themename.theme:

function themename_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
    switch ($hook) {
        case 'image_formatter':

            /**
             * @var Drupal\url_image\Plugin\Field\FieldType\UrlImageItem $item
             */
            $item = $variables['item'];
            $config = $item->getFieldDefinition();
            switch ($config->getTargetBundle()) {
                case 'b_partner_images':
                    $suggestions[] = 'image_formatter__b_partner_images';
                    break;
            }
            break;
    }
}

Create a template file image-formatter--b-partner-images.html.twig:

<a href="{{ url }}" title="{{ image['#alt'] }}" target="_blank">
     <div class="image" style="background-image: url('{{ file_url(image['#uri']) }}');"></div>
</a>

It works, but not as beautifully, as I would like.

PS: I used that specific hook_theme_suggestions_alter format, because I have more than one suggestions hook, and I put them inside this single function, so I can add more conditions with ease.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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