$build =
$this->entityTypeManager
->
getViewBuilder('media'
) ->
view($media,
$view_mode,
$langcode);
// Allows other modules to treat embedded media items differently.
$build['#embed'
] = TRUE;
// There are a few concerns when rendering an embedded media entity:
// - entity access checking happens not during rendering but during routing,
// and therefore we have to do it explicitly here for the embedded entity.
$build['#access'
] =
$media->
access('view', NULL, TRUE
);
// - caching an embedded media entity separately is unnecessary; the host
// entity is already render cached.
unset($build['#cache'
]['keys'
]);
// - Contextual Links do not make sense for embedded entities; we only allow
// the host entity to be contextually managed.
$build['#pre_render'
][] =
static::
class D '::disableContextualLinks';
// - default styling may break captioned media embeds; attach asset library
// to ensure captions behave as intended. Do not set this at the root
// level of the render array, otherwise it will be attached always,
// instead of only when #access allows this media to be viewed and hence
// only when media is actually rendered.