Daniel Favand
Solution Engineer at Sanity.io, helping clients build great content experiences.
Fetch content from the base locale regardless of whether the current document is the base or translation document
// declare a field that we will return, called "locales"
'locales':
// follow the __i18n_base reference to the base document if it exists
// otherwise assume we are in the base document and reference it (@)
coalesce(__i18n_base->, @)
// create a projection off the resulting document
{
// declare a field, locales, as an array
'locales': [
// first item uses values from the base document
{'locale': __i18n_lang, 'slug': slug.current },
// "..." includes the items in parenthesis in the parent array
...(
// expand the translations reference array
__i18n_refs[]->{
// for each document, pluck the locale and slug
'locale': __i18n_lang,
'slug': slug.current
}
)
]
// return just the value of the "locales" key
}.locales
'locales': coalesce(__i18n_base->, @){
'locales': [
{'locale': __i18n_lang, 'slug': slug.current },
...(
__i18n_refs[]->{
'locale': __i18n_lang,
'slug': slug.current
}
)
]
}.locales
*[slug.current == $slug]{
title,
body,
'slug': slug.current,
'locales': coalesce(__i18n_base->, @){
'locales': [
{'locale': __i18n_lang, 'slug': slug.current },
...(__i18n_refs[]->{
'locale': __i18n_lang,
'slug': slug.current
})
]
}.locales
}
This snippet can be used with the document internationalization plugin to fetch content from all locales of the current document, regardless of whether the current document is the base document or a translation.
This is necessary because you might use the same front-end code to fetch and render the content for the base document as you would for a translated document, but only the base document has a reference to all the translated versions.
This example particularly relies on the coalesce function
, which will attempt to follow a reference to the base document. This reference field only exists on a translated document. If that field doesn't exist, we assume we are on a base document, and use the @ this
operator to provide the base document directly.
This example uses slugs, but you could also fetch titles or any other field that may exist across different versions of the document.
Solution Engineer at Sanity.io, helping clients build great content experiences.
Using webhooks and the Sanity API, you can merge content changes and user information
Go to Getting user information with webhooksWe can turn off validation for fields using the same logic we use to hide them
Go to Optional validation for hidden fieldsSimplify finding the right document to select when you have multiple types
Go to Filtering results for reference selectors in arraysOne query to fetch the draft it it exists, and fall back to the published version of a document.
Go to Fetch the draft or published version of a document