How to render HTML markup with syntax highlighting in Sanity Studio?
You're looking for the @sanity/code-input plugin! This is exactly what you need to display HTML (or any code) with proper syntax highlighting and formatting in Sanity Studio.
Installation
First, install the plugin:
npm i @sanity/code-inputBasic Usage
Instead of using a text type, change your schema field to use the code type:
{
name: 'htmlContent',
title: 'HTML Content',
type: 'code',
options: {
language: 'html' // Sets HTML as the default language
}
}Advanced Options
The plugin supports several helpful options:
{
name: 'htmlContent',
title: 'HTML Content',
type: 'code',
options: {
language: 'html',
languageAlternatives: [
{title: 'HTML', value: 'html'},
{title: 'CSS', value: 'css'},
{title: 'JavaScript', value: 'javascript'}
],
withFilename: true, // Allows adding a filename to the code block
highlightedLines: true // Enables line highlighting
}
}The languageAlternatives option is particularly useful if you want editors to be able to switch between different languages in the Studio UI.
Using in Portable Text
If you want to add code blocks within rich text content, you can include it in an array field:
{
name: 'content',
title: 'Content',
type: 'array',
of: [
{type: 'block'},
{
type: 'code',
options: {
withFilename: true,
highlightedLines: true
}
}
]
}Frontend Rendering
When rendering on the frontend, the code input stores data in this structure:
{
_type: 'code',
language: 'html',
code: '<div>Your HTML here</div>',
filename: 'optional-filename.html' // if withFilename is enabled
}You'll need to implement a serializer to render it properly with your preferred syntax highlighting library (like Prism.js or highlight.js).
This plugin gives you proper syntax highlighting, line numbers, and a much better editing experience than a plain text field! You can find more details in the official plugin documentation.
Show original thread3 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.