0

I'm trying to get to the name of a media file in twig. The name is located at:

mediaitem[0]->#values[name][x-default]

in the rendered entity passed into the template with field_media_item|field_value.

2
  • 1
    Preprocess it and get the field value through the API.
    – Kevin
    Aug 26, 2022 at 21:44
  • You may also consider using twig_tweak.
    – sonfd
    Aug 27, 2022 at 17:22

1 Answer 1

1

You can access hash properties in Twig {{ foo['#bar'] }}, but not the internal (protected) '#values table of an entity. Look in the media entity for public methods starting with get.

In this case getName():

{{ media.getname }}

The question doesn't provide information about the context, but if it is for example a node then you can access media items like this:

{% for field_media_item in node.field_media %}
    {{ field_media_item.entity.getname }}
{% endfor %}

It's recommended to use a get method if the entity provides one, because they often contain extra logic. If you don't find a get method then access the field value directly:

{{ field_media_item.entity.name.value }}

Your Answer

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

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