Unlock seamless workflows and faster delivery with our latest releases- get the details

Querying references inside a Portable text field in Sanity

8 replies
Last updated: Jan 11, 2022
Following the field level translation documentation, I have a content object that contains the languages as keys. Normally I can access any field like this.

"content": coalesce(content[$lang], content.en)

This content is a Portable text field, and I want to query the current language or fallback, but I want to be able to reach the references inside that object, like referenced images.

Say I want to access this asset of
pageImage
that is a block inside `content`:

_type == "pageImage" => {

...,

"alt": coalesce(alt[$lang], alt.en),

"imageBlock": imageBlock {

"asset": asset->url,

"dimensions": asset->metadata.dimensions

},

},

This doesn’t work:


"content": coalesce(content[$lang], content.en) {

....,

_type == "pageImage" => {

...,

alt,

"imageBlock": imageBlock {

"asset": asset->url,

"dimensions": asset->metadata.dimensions

},

},

}

How would you query that?
Jan 11, 2022, 4:31 PM
Hi! Using
coalesce()
in this way should work fine. Which API version are you on?
Jan 11, 2022, 4:55 PM
The api version is “2021-03-25”
If I only query this

"content": coalesce(content[$lang], content.en) {

...,

}

I get null. Should I change the api version to something else?
Jan 11, 2022, 5:21 PM
Odd. That API version should work.
Jan 11, 2022, 5:31 PM
Can you do just:
"content": coalesce(content[$lang], content.en)
and see?

Also, if that returns null, how about just:

"content": coalesce(content[$lang])
Jan 11, 2022, 5:32 PM
"content": coalesce(content[$lang], content.en)
works well. the problem is that I cant access the reference of the images inside that object if I do only that.
Jan 11, 2022, 6:01 PM
In the output of content I will get
"imageBlock": {
        "_type": "image",
        "asset": {
          "_ref": "image-e54e00da4b0c81d18aea3260fd7a551b5f914121-702x490-gif",
          "_type": "reference"
        }
How do I access that reference?
Jan 11, 2022, 6:01 PM
I found the solution! After coalesce() I should query inside the array, not an object key.

"content": coalesce(content[$lang], content.en)[] {

...,

_type == "image" => {

...,

alt,

"imageBlock": imageBlock {

"asset": asset->url,

"dimensions": asset->metadata.dimensions

},

}

}
Jan 11, 2022, 6:08 PM
Ah, for some reason I thought
content[...]
was an object. 🙂 Great!
Jan 11, 2022, 6:13 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?