Work with the new Drupal Media Entities.

The new Media features in 8.8 core are great. I've been working with a commercial template that used the old school media field and trying to use Media Entities instead since they have so many potential advantages, including adding fields like keywords, captions, copyright, etc.

Getting added fields to show in Twig templates is...uh...exciting. The module Bamboo Twig can be really helpful. Here's some stuff I figured out when placed in a file node--myContentType.html.twig

  • To print the value of a field: 
    • {{ node.field_media_image.entity.field_myfield.value }}
  • To print the first keyword of a taxonomy term:
    • {{ node.field_media_image.entity.field_keywords.entity.name.0.value }}
  • A render array of a taxonomy term added to a media type. The 10 is the media item ID
    • {{ bamboo_render_field('field_keywords', 'media', 10) }}
  • Image alt tag from a Media Image entity: 
    • {{ node.field_media_image.entity.field_media_image.0.alt }}
  • URI of a media entity:
    • {{ node.field_media_image.entity.field_media_image.0.entity.uri.value }}
  • To render a media image using an image style:
    • <img src="{{ bamboo_render_image_style('public://2020-01/image.jpg', 'thumbnail') }}">
Tags