0

I have seen a lot of related answers to this question but nothing specific to my issue - apologies in advance if it has already been answered.

In Drupal 8, I have a custom block type that references a Paragraph type. The Paragraph has a field that references an image media bundle. So it looks something like this:

Block-> ReferenceFieldForParagraph-> Paragraph-> ReferenceFieldForMediaBundle-> MediaBundle-> ImageUploadField

I need to apply various image styles to that image and then get the URL for each image.

  • In the Paragraph's Display, I have set the field that references the media bundle to display Thumbnail: Original Image
  • I have created a twig template for the paragraph bundle and I am able to generate my various images by doing the following:

The media bundle reference field is named field_slide_image:

{% block paragraph %}
  {% block content %}

    {# set the styles #}
    {% set image1 = content.field_slide_image.0|merge({'#image_style': 'style1'}) %}
    {% set image2 = content.field_slide_image.0|merge({'#image_style': 'style2'}) %}
    {% set image3 = content.field_slide_image.0|merge({'#image_style': 'style3'}) %}

    {# render images #}
    {{ image1 }}
    {{ image2 }}
    {{ image3 }}

  {% endblock %}
{% endblock paragraph %}

I cannot figure out how to get the URL. I have tried to use file_url() but I don't see any reference to the uri when I use kint. In other words, something like this doesn't work:

{% set image1 = content.field_slide_image.0|merge({'#image_style': 'style1'}) %}
{% set uri1 = file_url(image1.uri.value)  %}
{{ uri1 }}

I need the url's so that I can create a custom responsive image using the picture tag. I need to generate this dynamically because I have another field (select box) that specifies the dimensions of the images (ie the image styles). For example, option 1 is a 1x1 ratio, option 2 is a 3x4 ratio, etc. I could easily print all images and set up media queries to hide/display them but I don't want to resort to that if I don't have to.

Here is what I see when I kint image1

kint

Thanks in advance

1

I wouldn't try to hack the render array content. You might be more successful with the paragraph entity:

{% set uri = paragraph.field_slide_image.0.entity.field_image_upload.entity.uri.value %}

{% set url1 = uri|image_style('style1') %}
{% set url2 = uri|image_style('style2') %}
{% set url3 = uri|image_style('style3') %}

For the filter image_style install the module Twig Tweak.

| improve this answer | |

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.