This is basically the same question as this, but I can't get the technique to work in a custom block type template: https://drupal.stackexchange.com/a/219052/71100
- I have a custom block type called
link_card
. - I have an image field
field_link_card_image
. - I have a List(text) field to select an image style
field_link_card_size
- I have confirmed that
field_link_card_size
is outputting the key, which is the machine name of my image style. - My theme template is
block--bundle-link-card.html.twig
. It overridesblock.html.twig
. The template is working. - I want to render the image and use the image size selected.
Here is the first way I tried based on what worked in the answer for page.html.twig
.
{% set image = {
'#theme': 'image_style',
'#style_name': content.field_link_card_image_size[0],
'#uri': file_url(content.field_link_card_image['#items'].entity.uri.value),
'#alt': content.field_link_card_image[0].alt,
} %}
{{ image }}
I get this white screen error:
Error: Call to a member function transformDimensions() on null in template_preprocess_image_style() (line 303 of core/modules/image/image.module).
And this error in Report Log in the admin area:
Warning: array_flip(): Can only flip STRING and INTEGER values!
If I replace the value for '#style_name:
with the just the machine name of one of my image styles (such as square
) it almost kinda works.
- The image renders but with the _incorrect image src:
/D8_1318_LinkCard/web/files/styles/square/public//D8_1318_LinkCard/web/files/2019-06/unsplash_1500x500-4.jpg?itok=c16MdkOY
(You can see it's sort of repeated itself.) - The alt text doesn't come in at all, so I probably have that wrong, too.
This leads me to believe that there are problems how I'm pulling in the field content from the block.
Here is the second way I tried:
{% set image = content.field_link_card_image[0] %}
{% set imagestyle = content.field_link_card_image_size[0] %}|
{% set image = setimage|merge({ '#image_style': imagestyle }) %}
{{ image }}
The errors are:
Error: Call to a member function transformDimensions() on null in template_preprocess_image_style() (line 303 of core/modules/image/image.module).
and
Warning: array_flip(): Can only flip STRING and INTEGER values!
and
Error: Call to a member function transformDimensions() on null in template_preprocess_image_style()
This works if I do imagestyle = 'square'
. But of course I'm trying to use the value of the field.
Here the problem seems to be an issue with getting in the field_image size to sneak into the variable imagestyle
.
TLDR: How do I render an image field with a custom style in the custom block template.
Thanks!