Skip to content
Sveltia CMS
Esc
↑↓navigate↵open⌘Jpreview
On this page

Rendering Markdown

Render the Markdown value of a RichText field in your own preview with the same pipeline as the Sveltia CMS Preview Pane, or convert it to HTML.

The value of a RichText or Markdown field is a Markdown string. You may render such a value yourself, for example in:

In that case, the string is used as is, so text like **bold** appears verbatim unless you convert it to HTML.

Overview

Sveltia CMS offers two ways to do that. Both are available as soon as the CMS is loaded, whether you use the CDN build or the npm package. No additional dependency is necessary:

  • CMS.renderRichText() renders the value into a DOM element you provide, exactly like the built-in Preview Pane — custom editor components, images and sanitization included. Use it whenever you have an element to render into.
  • marked and DOMPurify are the parser and sanitizer the CMS uses internally, exposed on the window object. Use them when you need an HTML string, such as for a React component.

Using renderRichText

The CMS.renderRichText() method renders a Markdown string into a DOM element you provide, using the same pipeline as the Preview Pane of a RichText field:

  • Custom editor components are rendered with their own toPreview output, including components nested in the value, recursively
  • Markdown is parsed into HTML, with a single line break becoming a <br>
  • Code blocks are syntax-highlighted
  • Internal image paths are replaced with blob URLs, so uploaded images appear in the preview
  • The resulting HTML is sanitized

It takes the target element, the Markdown string and an optional options object. It returns a function that removes the rendered content and destroys any component previews within it:

const destroy = CMS.renderRichText(element, markdown, options);

The content is rendered asynchronously. The target element doesn’t have to be attached to the document yet when you call the method. For example, it can be an element created in toPreview that the CMS inserts into the Preview Pane afterwards.

The options object accepts the following property:

  • fieldConfig — RichText field options to be applied, such as editor_components to restrict the available components and sanitize_preview to disable sanitization. Options not given here fall back to the field_defaults configuration. The exception is sanitize_preview: the output is sanitized unless it’s explicitly set to false here.

The method is designed for an editor component whose toPreview returns a DOM element. There, the value of a nested RichText field would otherwise be displayed verbatim.

Call the returned destroy function once the CMS dispatches the Unmount event on the element, so that the nested previews are destroyed along with your component:

import { registerEditorComponent } from '@sveltia/cms';
import { mount, unmount } from 'svelte';
import Warning from '$lib/components/Warning.svelte';

registerEditorComponent({
  id: 'warning',
  label: 'Warning',
  icon: 'warning',
  fields: [{ name: 'body', label: 'Body', widget: 'richtext' }],
  pattern: /<Warning>\s*(?<body>[\s\S]*?)\s*<\/Warning>/,
  toBlock: ({ body = '' }) => `<Warning>\n\n${body}\n\n</Warning>`,
  toPreview: ({ body = '' }) => {
    const element = document.createElement('div');
    const component = mount(Warning, { target: element, props: { body } });

    element.addEventListener('Unmount', () => unmount(component), { once: true });

    return element;
  },
});
CMS.registerEditorComponent({
  id: 'warning',
  label: 'Warning',
  icon: 'warning',
  fields: [{ name: 'body', label: 'Body', widget: 'richtext' }],
  pattern: /<Warning>\s*(?<body>[\s\S]*?)\s*<\/Warning>/,
  toBlock: ({ body = '' }) => `<Warning>\n\n${body}\n\n</Warning>`,
  toPreview: ({ body = '' }) => {
    const element = document.createElement('div');
    const destroy = CMS.renderRichText(element, body);

    element.className = 'bg-red-100';
    element.addEventListener('Unmount', destroy, { once: true });

    return element;
  },
});

In the Svelte example, the component itself calls the method with an attachment, which runs the returned destroy function automatically when the component is unmounted:

<script>
  import { renderRichText } from '@sveltia/cms';

  let { body } = $props();
</script>

<div class="bg-red-100" {@attach (element) => renderRichText(element, body)}></div>

The nested value goes through the same component matching as the field itself. A component can therefore contain other components, or even another instance of itself. This works as long as the pattern of each component can match its own block within the parent’s. Any nested component preview is rendered in place, whether it returns a string, a DOM element or a React element.

Using marked and DOMPurify

You may need an HTML string rather than a rendered element, for example to pass it to a React component’s dangerouslySetInnerHTML prop. For that, Sveltia CMS exposes the two libraries it uses internally, so you don’t need to add a dependency of your own:

  • marked — The Marked parser, which converts a Markdown string to an HTML string
  • DOMPurify — The DOMPurify sanitizer, which strips scripts and other dangerous markup from an HTML string

These are available on the window object when Sveltia CMS is loaded, whether you use the CDN build or the npm package. No additional imports are necessary to use them.

const html = DOMPurify.sanitize(marked.parse(markdown));

The CMS renders the Preview Pane with the breaks option enabled, meaning a single line break becomes a <br>. Pass the same option if you want your output to match:

const html = DOMPurify.sanitize(marked.parse(markdown, { breaks: true }));

Note that, unlike renderRichText, this approach doesn’t render custom editor components or resolve internal image paths. The value is converted as plain Markdown.

Was this page helpful?