Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Get image URL from media field in twig

Parent Feed: 

Apparently there are still pretty common Drupal 8 theming tasks that cannot be accomplished with the great twig_tweak module. This by the way was me giving a plug to a great little module, which makes half of all your theme preprocess hooks unnecessary.

Update: Apparently there is a module like twig_tweak but with the ability to do the above. It is called bamboo_twig and its documentation can be found here - thanks to Luckhardt Labs for mentioning it. Mind you I have not tested it yet. There is a rather interesting issue in its queue about the lack of collaboration between the two module maintainers.

If you would like to get the URL from an image that is trapped inside of a media entity however, you can either extract it using the aforementioned preprocess function like so:

  1. function mytheme_preprocess_node(&$variables) {

  2. /** @var \Drupal\node\NodeInterface $node */

  3. $node = $variables['node'];

  4. $image_field = $node->get('field_background_image');

  5. if (!$image_field->isEmpty()) {

  6. $uri = $image_field->entity->get('field_media_image')->entity->uri->value;

  7. $variables['background_image_url'] = file_create_url($uri);

  8. }

  9. }

In the node template, you can display it using

  1. {{ background_image_url }}

... or use this nifty snipplet inside of your twig template directly:

  1. {% if node.field_background_image is not empty %}
  2. {{ file_url(node.field_background_image.entity.field_media_image.entity.fileuri) }}

In this case the media image URL is acquired from a node inside of a node tempalate node--node-type.html.twig, but this will work for other entities in other templates as well, e.g a paragraph in paragraph--paragraph-type.html.twig.

Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web