0

I would like to print an image URL with an image-style. This doesn't work, since I don't have a ".value"-value for the image: How to find image style URL from within twig template?

Is there anything different on field-templates?

My code in field--field-images.html:

{% for item in items %}
    <img src="{{ item.content['#url'].uri }}">
{% endfor %}

This doesn't work (results in no filename since .value isn't available:

<img src="{{ item.content['#url'].uri.value  | image_style('image_style') }}">

This crashes the page:

<img src="{{ item.content['#url'].uri | image_style('image_style') }}">

Thanks!

5
  • 2
    Possible duplicate of Render Teaser Image in search block using Twig
    – Hudri
    Commented Apr 25, 2019 at 13:22
  • 1
    Don't do this with template code, configure the proper image style in Admin > Structure > Content types > (your bundle) > Manage display
    – Hudri
    Commented Apr 25, 2019 at 13:25
  • 1
    Just let it render normally and use the display config proper.
    – Kevin
    Commented Apr 25, 2019 at 16:38
  • I forgot to say: there's lots of other custom-code in the template file, so I can't use the display configured in the display-settings.
    – Arerrac
    Commented Apr 26, 2019 at 14:30
  • Have you tried something like this: drupal.stackexchange.com/questions/219039/… Otherwise the only way I can think of is to use a preprocess to add a variable to the template. Commented Nov 2, 2020 at 9:51

1 Answer 1

0

Change the display mode of your field with the image style you want. And it's ok

But If you want do this with a custom module, you can do this:

$imageFile = Media::load($media_mid);
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$imageThumbnailUri = $style->buildUrl($imageFile->get('thumbnail')->entity->getFileUri());

Your Answer

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

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