1

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?

  • Why not just render the media object itself and let the field formatter on the image field do that work? – Kevin Dec 9 '17 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 '17 at 18:53
3

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.

  • 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 '17 at 16:22

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.