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

Query for slugs for all available locales of this document

By Daniel Favand

Fetch content from the base locale regardless of whether the current document is the base or translation document

Annotated GROQ snippet

 // 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

Same snippet, more compact

 'locales': coalesce(__i18n_base->, @){
       'locales': [
         {'locale': __i18n_lang, 'slug': slug.current },
         ...(
          __i18n_refs[]->{
            'locale': __i18n_lang, 
            'slug': slug.current 
          }
         )
        ]
     }.locales

Full example query

*[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.

Contributor

Other schemas by author