Converts from Markdown to HTML fully client-side
Last modified by superadmin on 2026/11/25 21:38
Content
Markdown content turned into HTML in the browser, through the universal AST.
Steps
Follow the steps in the comments of the snippet below.
import { Container } from "inversify";
import type { UniAstToHTMLConverter } from "@xwiki/cristal-uniast-html";
import type { MarkdownToUniAstConverter } from "@xwiki/rendering-uniast-markdown";
async function markdownToHTML(
source: string,
container: Container,
): Promise<string> {
// Mardown to uniast to html
// Step 1: resolve the markdown parser
const md = container.get<MarkdownToUniAstConverter>(
"MarkdownToUniAstConverter",
);
// Step 2: parse the markdown to get a uniast object
const uniAst = await md.parseMarkdown(source);
if (uniAst instanceof Error) {
throw uniAst;
}
// Step 3: resolve the html serializer
const html = container.get<UniAstToHTMLConverter>("UniAstToHTMLConverter");
// Step 4: serialize the uniast object to HTML
const toHtml = html.toHtml(uniAst);
if (toHtml instanceof Error) {
throw toHtml;
}
return toHtml;
}