Knut Melvær
Knut is a principal developer marketing manager at Sanity.io
Schemas for adding richer quotes within Portable Text
// quote.js
export default {
name: 'quote',
type: 'object',
title: 'Quote',
fields: [
{
name: 'text',
type: 'text', // <= This can also be a Portable Text field
title: 'Text',
},
{
name: 'author',
type: 'string', // <= This could be a reference to an author document type, if you had that
title: 'Author',
},
{
name: 'url',
type: 'url',
title: 'URL',
description: 'Source on the web',
}
]
}
// portableText.js
export default {
name: 'portableText',
type: 'array',
title: 'Portable Text',
of: [
{
type: 'block',
},
{
type: 'quote',
}
]
}
// portableText.jsx
export const serializers = {
type: {
quote: ({ node: { text, author, url } }) => {
return (
<figure>
<blockquote cite={url}>
{text}
</blockquote>
{author && <figcaption>{author}</figcaption>}
</figure>
)
}
}
}
// Query for documents with more than 5 quotes in them. Given the portable text field is named “body”
*[count(body[_type == "quote"]) > 5]{
_id,
_type,
"quotes": body[_type == "quote"].text
}
// Query for documents that has a quote by "Ursula K. Le Guin”
*["Ursula K. Le Guin" in body[_type == "quote"].author]{
_id,
_type,
"quotes": body[_type == "quote"].text
}
This is an example of how to make a rich “quotation” block in Portable Text. It supports adding the author of the quote as well as an URL on the web.
You can customize this pattern to be more advanced by replacing the text
field with a Portable Text field allowing for marks. The author
field can also be a reference to another document type in cases where you have the quoted person as a resource in the Content Lake.
There's also an example of how to serialize this with JSX using the best HTML markup I could find (there might be better ways though).
This pattern also allows for querying your content lake by how many quotes there are, or by specific fields like quotes by a certain author.
Knut is a principal developer marketing manager at Sanity.io
This can be used for blogs or articles where you want to possibly display next and previous article buttons
Go to Get current post, previous post, and next postHow to automatically generate linked headings with a custom serializer
Go to Anchored Headings for Portable TextMigration script to convert plain text to block content across your content lake
Go to Migrate plain text field to Portable TextSimple content type for a question and answer pattern
Go to Frequently asked questions