How to render HTML markup with syntax highlighting in Sanity Studio?

3 replies
Last updated: Jun 14, 2021
Hi everyone!
I'm using a text type to store html markup, is there a way to render it as code in the Studio? For instance, with code formatting, colors, etc?
AI Update

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-input

Basic 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 thread
3 replies
Sweet! Thanks, I should have looked more carefully đź‘€
Not to worry! It’s usually not obvious when something’s built in and when reaching out for a plugin is needed. Glad that will work for you! 🙂

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?