Get Image URL From Referenced Media Into View In Drupal 8

February 14th, 2019  | Categories: Drupal, Drupal 8, Pattern Lab

I have a view of all blog posts. Each blog post has an image which is a referenced Media. On the view of all the blog posts, I would like to use a Pattern Lab template. So, I need to pass an image URI to a Pattern Lab template. However, when I add the image to the Fields in the view, it outputs the image with no option of outputting the URI of the image.

I forget if there was a way to do this without a custom module in D7. D8 does offer a custom module to do this but come on! This is so simple! We shouldn’t have to have a custom module just to output the src of an image!

What I finally figured out how to do (after looking at a few forums) is to add a relationship to the media.

In the view, follow these steps:

  1. Expand Advanced on the right side.
  2. Click Add to the right of Relationships.
  3. Choose Media referenced from field_image (where field_image may be what the field is for your content type.)
    Screen shot of Media referenced from field_image
  4. Apply (to this display).
  5. Under Fields click Add.
  6. Search for image and select the Image with category Media.
    Screen shot of Image with Media category
  7. On the next screen for Formatter choose URL to image.

There you go! You should see the path to the image and NOT the stupid public:// path either!

Getting it from the twig template was difficult too but here’s how I got it:

{{ fields.field_media_image.content|striptags|trim }}

Why striptags and trim? Cause if you have suggestion comments on (like I do), it is outputting a field so you want to get rid of that and just have the string itself.

Now you can pass that pretty output into your pattern lab template or do whatever you want with it!

No comments yet.