Last active
October 27, 2022 08:11
-
-
Save hagemann/9e3d53b93ece55e77332d2594ffda43c to your computer and use it in GitHub Desktop.
Render EditorJS blocks to HTML.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const renderHtml = (blocks) => { | |
var html = blocks.map(block => { | |
switch (block.type) { | |
case 'code': | |
return `<pre><code>${ block.data.code }</pre></code>` | |
/** | |
* Original type is 'header' but I renamed the block to follow correct terminology: | |
* https://github.com/editor-js/header/issues/21 | |
*/ | |
case 'heading': | |
return `<h${ block.data.level }>${ block.data.text }</h${ block.data.level }>` | |
case 'image': | |
var classes = [] | |
if (block.data.stretched) { | |
classes.push('stretched') | |
} | |
if (block.data.withBorder) { | |
classes.push('border') | |
} | |
if (block.data.withBackground) { | |
classes.push('bg-light') | |
} | |
return `<figure><img class="${ classes.join(' ') }" src="${ block.data.file.url }" style="max-width: 100%;">${ caption }</figure>` | |
case 'list': | |
var listItems = block.data.items.map(item => { | |
return `<li>${ item }</li>` | |
}) | |
if (block.data.style === 'ordered') { | |
return `<ol>${ listItems.join('') }</ol>` | |
} | |
if (block.data.style === 'unordered') { | |
return `<ul>${ listItems.join('') }</ul>` | |
} | |
case 'paragraph': | |
return `<p>${ block.data.text }</p>` | |
case 'quote': | |
if (block.data.caption) { | |
var caption = `<footer>${ block.data.caption }</footer>` | |
} | |
return `<blockquote>${ block.data.text }${ caption }</blockquote>` | |
case 'raw': | |
return block.data.html | |
case 'table': | |
var tableRows = block.data.content.map(row => { | |
var tableCells = row.map(cell => `<td>${ cell }</td>`) | |
return `<tr>${ tableCells.join('') }</tr>` | |
}) | |
return `<table><tbody>${ tableRows.join('') }</tbody></table>` | |
} | |
}) | |
return html | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment