Skip to content

Instantly share code, notes, and snippets.

@StanisLove
Forked from hagemann/blocksToHtml.js
Created August 18, 2020 10:14
Show Gist options
  • Save StanisLove/575111878656d3b6fa0aa796f7f66cb8 to your computer and use it in GitHub Desktop.
Save StanisLove/575111878656d3b6fa0aa796f7f66cb8 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