Skip to content

Instantly share code, notes, and snippets.

@hagemann
Last active October 27, 2022 08:11
Show Gist options
  • Save hagemann/9e3d53b93ece55e77332d2594ffda43c to your computer and use it in GitHub Desktop.
Save hagemann/9e3d53b93ece55e77332d2594ffda43c to your computer and use it in GitHub Desktop.
Render EditorJS blocks to HTML.
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