πŸ‘€ Our most exciting product launch yet πŸš€ Join us May 8th for Sanity Connect

Block Content rendering: Image materializing

The image type holds a set of user-defined fields as well as an asset field which is a reference to the actual asset document. Quite often you will need to get ahold of the asset document in order to make decisions based on the size, name, type, or metadata of the image, or to get the full URL to the image.

Joining the asset document using GROQ

You can join these references when you fetch the document(s) containing a Portable Text field. Let's say you have a document type named article which has a body field containing an array of blocks. The following query would expand all the asset fields within the array:

*[_type == "article"]{
  body[]{
    ..., 
    asset->{
      ...,
      "_key": _id
    }
  }}[0...5]

Let's break it down:

  • Fetch all documents of type article: *[_type == "article"]
  • For each item in the body array: body[]
  • Return all the properties: ...
  • Make a property called asset and let the value be the materialized value of the asset property: "asset" asset->
  • Only return the 5 first documents matched: [0...5]

More information on querying data

Looking to get started working with data from your Sanity data store? Find out how GROQ queries work or dive in with Sanity's GraphQL interface.

Was this article helpful?