Add inline variable/shortcode in rich text editor
Yes, absolutely! You can add inline variables/shortcodes in Sanity's rich text editor using custom annotations in Portable Text. Annotations let you embed structured data directly within text spans, which is perfect for creating dynamic variables or shortcodes.
Creating a Custom Variable Annotation
In your schema, define a custom annotation type within your block content field. Here's an example for a "variable" shortcode:
defineField({
name: 'content',
type: 'array',
of: [
{
type: 'block',
marks: {
annotations: [
{
name: 'variable',
type: 'object',
title: 'Variable',
icon: () => '{{}}',
fields: [
{
name: 'key',
type: 'string',
title: 'Variable Key',
description: 'The variable identifier (e.g., "firstName", "companyName")',
},
{
name: 'fallback',
type: 'string',
title: 'Fallback Text',
description: 'Text to display if variable is not available',
}
]
}
]
}
}
]
})How It Works in the Editor
Editors can highlight any text in the rich text editor and apply your custom annotation (it'll appear in the toolbar). When they select it, they can configure the variable key and fallback text in a popup form. The annotated text will be visually marked in the editor.
Rendering on the Frontend
When rendering your Portable Text, you'll need a custom serializer to handle your variable annotations. Here's an example using React:
import {PortableText} from '@portabletext/react'
const components = {
marks: {
variable: ({value, children}) => {
// Look up the actual variable value from your data
const variableValue = lookupVariable(value.key) || value.fallback
return <span className="variable">{variableValue}</span>
}
}
}
<PortableText value={content} components={components} />This approach gives you full flexibility - you can create variables for personalization, dynamic content, or any other use case where you need to inject values into rich text. The annotations are stored as structured data in the markDefs array, making them queryable and reusable across different platforms.
You can read more about implementing custom annotations in the Ultimate Guide for Customising Portable Text.
Show original thread6 replies
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.