4

I have a media entity target id and I want to render the image contained in it. I've loaded the media entity using Media::load, I was hoping to use something like render() on some rendererable array that I can extract/generate from that media entity object. I found a somehow related question here: How to get Media entity image (Entity Reference Field) URL in TWIG theme, using ImageStyle::load, but I want to render the whole image with its defined attributes (alt, title or fields). Any suggestions please?

2
  • Why not just render the media object itself and let the field formatter on the image field do that work?
    – Kevin
    Dec 9, 2017 at 18:07
  • Well because it is an object and I need the renderable array of the media. \Drupal::service('renderer')->render($media) render function only accepts an array, I think.
    – foopal
    Dec 9, 2017 at 18:53

2 Answers 2

8

You need to build a render array

$build = \Drupal::entityTypeManager()->getViewBuilder('media')->view(‌$media, $view_mode);

and then place it unrendered in a template, Twig renders this automatically.

1
  • Thank you, just what I was looking for! In fact, I wanted it rendered to get the whole html code from js. I could have passed only the media URI, but I needed the defined media attributes as alt for eg.
    – foopal
    Dec 10, 2017 at 16:22
1

Using the twig_tweak module, I found I could use:

<dd>{{ drupal_field('field_image', 'node') }}</dd>

Your Answer

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

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