Wiki source code of Converts from Markdown to HTML fully client-side
Last modified by Manuel Leduc on 2026/02/05 17:22
Hide last authors
| author | version | line-number | content |
|---|---|---|---|
| |
1.1 | 1 | The snippet below presents how to parse Markdown content and convert it to HTML. |
| |
3.1 | 2 | You can follow the steps mentionned in the snippet's comments. |
| |
1.1 | 3 | |
| 4 | {{code language="typescript"}} | ||
| 5 | import { Container } from "inversify"; | ||
| 6 | import type { UniAstToHTMLConverter } from "@xwiki/cristal-uniast-html"; | ||
| 7 | import type { MarkdownToUniAstConverter } from "@xwiki/rendering-uniast-markdown"; | ||
| 8 | |||
| 9 | async function markdownToHTML( | ||
| 10 | source: string, | ||
| 11 | container: Container, | ||
| 12 | ): Promise<string> { | ||
| 13 | // Mardown to uniast to html | ||
| |
3.1 | 14 | // Step 1: resolve the markdown parser |
| |
1.1 | 15 | const md = container.get<MarkdownToUniAstConverter>( |
| 16 | "MarkdownToUniAstConverter", | ||
| 17 | ); | ||
| 18 | |||
| |
3.2 | 19 | // Step 2: parse the markdown to get a uniast object |
| |
1.1 | 20 | const uniAst = await md.parseMarkdown(source); |
| 21 | |||
| 22 | if (uniAst instanceof Error) { | ||
| 23 | throw uniAst; | ||
| 24 | } | ||
| |
3.1 | 25 | |
| 26 | // Step 3: resolve the html serializer | ||
| |
1.1 | 27 | const html = container.get<UniAstToHTMLConverter>("UniAstToHTMLConverter"); |
| |
3.1 | 28 | // Step 4: serialize the uniast object to HTML |
| |
1.1 | 29 | const toHtml = html.toHtml(uniAst); |
| 30 | if (toHtml instanceof Error) { | ||
| 31 | throw toHtml; | ||
| 32 | } | ||
| 33 | return toHtml; | ||
| 34 | } | ||
| 35 | {{/code}} |