UNPKG

blocks-html-renderer

Version:

Render the content of Strapi's Blocks rich text editor as HTML in your frontend.

85 lines 2.59 kB
// src/index.ts var renderChildren = (children) => { let html = ""; children.forEach((child) => { if (child.type === "text") { html += renderText(child); } else if (child.type === "link") { html += `<a href="${child.url}">${renderChildren(child.children)}</a>`; } else if (child.type === "list-item") { html += `<li>${renderChildren(child.children)}</li>`; } }); return html; }; var renderText = (node) => { let html = node.text; if (node.bold) { html = `<strong>${html}</strong>`; } if (node.italic) { html = `<em>${html}</em>`; } if (node.underline) { html = `<u>${html}</u>`; } if (node.strikethrough) { html = `<s>${html}</s>`; } if (node.code) { html = `<code>${html}</code>`; } return html; }; var renderBlock = (block) => { if (!block) return ""; let html = ""; block.forEach((block2) => { if (block2.type === "paragraph") { html += `<p>${renderChildren(block2.children)}</p>`; } else if (block2.type === "quote") { html += `<blockquote>${renderChildren(block2.children)}</blockquote>`; } else if (block2.type === "code") { html += `<pre><code>${renderChildren(block2.children)}</code></pre>`; } else if (block2.type === "heading") { switch (block2.level) { case 1: html += `<h1>${renderChildren(block2.children)}</h1>`; return; case 2: html += `<h2>${renderChildren(block2.children)}</h2>`; return; case 3: html += `<h3>${renderChildren(block2.children)}</h3>`; return; case 4: html += `<h4>${renderChildren(block2.children)}</h4>`; return; case 5: html += `<h5>${renderChildren(block2.children)}</h5>`; return; case 6: html += `<h6>${renderChildren(block2.children)}</h6>`; return; } } else if (block2.type === "link") { html += `<a href="${block2.url}">${renderChildren(block2.children)}</a>`; } else if (block2.type === "list") { if (block2.format === "ordered") { html += `<ol>${renderChildren(block2.children)}</ol>`; } else { html += `<ul>${renderChildren(block2.children)}</ul>`; } } else if (block2.type === "list-item") { html += `<li>${renderChildren(block2.children)}</li>`; } else if (block2.type === "image") { html += `<img src="${block2.image.url}" alt="${block2.image.alternativeText || void 0}" />`; } }); return html; }; export { renderBlock }; //# sourceMappingURL=index.mjs.map