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 Answers
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.– foopalDec 10, 2017 at 16:22
Using the twig_tweak module, I found I could use:
<dd>{{ drupal_field('field_image', 'node') }}</dd>
\Drupal::service('renderer')->render($media)
render function only accepts an array, I think.