Help articles

Materialize image assets in a Portable Text query

The image type holds your user-defined fields alongside four built-in ones: asset, media, hotspot, and crop. The asset field is a reference to the actual asset document. Quite often you need to access the asset document to make decisions based on the size, name, type, or metadata of the image, or to get the full URL to the image.

Join the asset document with GROQ

You can join these references when you fetch the documents containing a Portable Text field. Let's say you have a document type named article with a body field containing an array of blocks. The following query materializes the asset reference on every image block in that array:

Let's break it down:

  • Fetch all documents of type article: *[_type == "article"]
  • Include the document's own fields so each result is identifiable: _id, title
  • For each item in the body array: body[]
  • Return all the properties of each block: ...
  • For image blocks only, replace the asset reference with the fields you need from the document it points to: _type == "image" => {asset->{...}}
  • Return only the first five documents matched: [0...5]

Scoping the join to image blocks matters. An unscoped asset-> adds an "asset": null property to every text block in the array. A bare asset-> also returns the whole asset document, including the color palette and a base64 metadata.lqip preview string, so project only the fields you need.

Learn more about GROQ

GROQ is the recommended way to query content in the Content Lake. Find out how GROQ queries work, or see Sanity's GraphQL API for a schema-typed alternative.

Was this page helpful?