Sanity Helper Functions
- #Tips & Tricks
![Bill Murray holding a sign that says "Don't Repeat Yourself", a ground hog sticking his head out of the ground, film still from the movie Ground Hog day](https://cdn.sanity.io/images/elyfelq1/production/d75bab64239eb00db9b7b71634b2b5364ba20d6d-1344x896.jpg?w=1500&auto=format)
An important rule in programming is: DRY
Don't Repeat Yourself
This starter template comes included with a number of helper functions to use in your Sanity Studio so you don't have to repeat yourself.
Structure Helpersđ
Customizing and organizing your Sanity Studio structure (where your content lives) is super easy. Here's a handy cheat sheet, too.
Singletonđ
đ sanity/src/structure.ts
import { singleton } from './utils'
S.list()
.title('Content')
.items([
// ...
singleton(S, 'yourDocumentId').icon(...)
])
Groupđ
đ sanity/src/structure.ts
import { group } from './utils'
S.list()
.title('Content')
.items([
// ...
group(S, 'Group name', [
S.documentTypeListItem('logo').title('Logos'),
S.documentTypeListItem('testimonial').title('Testimonials'),
]).icon(...),
])
Preview Helpersđ
Customizing previews are also super easy. Here's official documentation on that.
Converting PortableText to a stringđ
import { getBlockText } from '@sanity/src/utils'
preview: {
select: {
content: 'content' // this is a block type (a.k.a. PortableText)
},
prepare: ({ content }) => ({
title: getBlockText(content)
})
}
![Preview of portable text when used with the helper function](https://cdn.sanity.io/images/elyfelq1/production/6463a3d2855531ec6a8d4753659cbcc60a4ee7ae-1268x338.jpg?w=1500&auto=format)
Item countđ
import { count } from '@sanity/src/utils'
preview: {
select: {
items: 'items' // this is an array type
},
prepare: ({ items }) => ({
title: count(items) // 1 item, 2 items
title: count(items, 'pikachu') // 1 pikachu, 2 pikachus
title: count(items, 'octopus', 'octopi') // 1 octopus, 2 octopi
})
}
Source Codeđ
The source code for all helper functions can be found here.
![Doc and Marty McFly in shocked expressions, with the title text "Repeat Yourself" in the style of the Back to the Future movie logo](https://cdn.sanity.io/images/elyfelq1/production/eee11804e297c873835f2c14f9d876450e9fdc4b-1344x896.jpg?w=1500&auto=format)