How to Concatenate 2 Values for the Preview Title

2 replies
Last updated: Jun 13, 2022
hey all, is it possible to concatenate 2 values for the
preview
title ? In my case I'd like to merge the number into the title such that it could appear on the left as "172 - Il faut que tu ruines tout". Thanks!
Second question, is
this really the only way to go about creating singleton pages in Sanity? seems awfully convoluted.. there must be a better way, no?
AI Update

Question 1: Concatenating values in preview titles

Absolutely! You can concatenate values in the preview title using the prepare function. Here's how to merge your number with the title:

preview: {
  select: {
    title: 'title',
    number: 'number'
  },
  prepare({title, number}) {
    return {
      title: `${number} - ${title}`
    }
  }
}

This will give you exactly what you want: "172 - Il faut que tu ruines tout" appearing in the document list. The prepare function lets you transform any selected fields before display, so you can concatenate, format, or manipulate the values however you need.

You can also add subtitles, media, or other fields:

preview: {
  select: {
    title: 'title',
    number: 'number',
    media: 'image'
  },
  prepare({title, number, media}) {
    return {
      title: `${number} - ${title}`,
      subtitle: 'Episode',
      media: media
    }
  }
}

Question 2: Singleton documents

I hear you – the singleton pattern does feel a bit involved! Unfortunately, yes, the manual configuration approach is the standard way in Sanity v3. You need to configure three things in your sanity.config.js:

  1. Structure builder to create a direct link
  2. Template filtering to hide it from the "New document" menu
  3. Document actions to remove duplicate/delete options

However, there's good news: you can use the singleton-tools plugin which handles all this configuration automatically. It's much less convoluted:

npm install @sanity/singleton-tools

Then in your config:

import {singletonTools} from '@sanity/singleton-tools'

export default defineConfig({
  // ... other config
  plugins: [
    singletonTools(),
  ],
})

This plugin wraps up all that boilerplate into a simpler interface. The manual approach gives you more control, but for most use cases, the plugin is the way to go and makes singletons much more straightforward to work with.

You can use
prepare()
to reformat your preview, like this
preview: {}
You can use
prepare()
to reformat your preview, it’s all well documented here: https://www.sanity.io/docs/previews-list-views

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?