I have a node that has an entity reference field to a Media entity. That media entity has a field on it "caption". I want to render this caption directly in my twig template, so instead of doing this:
{{ content.field_media_item }}
Which would output the entire rendered media entity, I just want to output a field from that media entity. I've tried this:
{{ content.field_media_item[0]['#media'].field_caption.value }}
Which works, but since it's already rendered output, all the HTML from that value is escaped. So <p>
tags appear as literal <p>
. I could tack on a |raw
at the end, which actually seems safe to me since I know the output has already been rendered and passed thru the field formatter, but seems wrong?
What's a better way of doing this? Using a pre-processor to access the field data from the reference media entity and passing it through a field formatter again or something? That actually seems inefficient since the caption field data was already rendered properly, and I'd be passing it thru the formatter again.
|raw
is definitely a security problem here, because#media
is not a field formatter, this is an entity and you get the value directly from the database.