How to grab image metadata from images inserted into Content blocks?

7 replies
Last updated: Sep 28, 2020

I’d really like to be able to grab image metadata from images inserted into Content blocks, but all I seem to be able to get back is a reference. How can I expand references contained inside portable text blocks?

Sep 28, 2020, 7:09 AM

Hi Andrew, have you tried something like this? If

content
is your block content field:
*[_type == "post"]{
  ...,
  "content": content[] {
    ...select(
      _type == "image" => {
        ...,
        "asset": asset->
      } 
    )
  }
}

Sep 28, 2020, 8:24 AM

Hi Andrew, have you tried something like this? If

content
is your block content field:
*[_type == "post"]{
  ...,
  "content": content[] {
    ...select(
      _type == "image" => {
        ...,
        "asset": asset->
      } 
    )
  }
}

Sep 28, 2020, 8:24 AM

You have awesome timing, I was just cobbling together something like this from what I could deconstruct from https://www.sanity.io/docs/presenting-block-text — but you helped me get the last piece in place

Sep 28, 2020, 8:31 AM

oddly enough, going off the examples, I ended up forming a query much like what you’ve got up there, except without the

…select
, but the the same contents inside the parentheses. It doesn’t seem to make a difference whether I use the
select
operator, I’m curious what that does here?

Sep 28, 2020, 8:32 AM

(also thank you! 🙏 )

Sep 28, 2020, 8:38 AM

Glad it’s working! If you’re not using

select
, you might be using the short-hand notation instead. Check out the part where it says:
// Projections also have syntactic sugar for inline conditionals
https://www.sanity.io/docs/query-cheat-sheet#conditionals-64a36d80be73

Sep 28, 2020, 8:56 AM

Brilliant. Makes perfect sense.

Sep 28, 2020, 9:01 AM

Sanity.io: Get the most out of your content

Sanity.io is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. Sanity.io comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Sanity.io. Free to get started, pay-as-you-go on all plans.