sanity-io / block-content-to-html

Deprecated in favor of @portabletext/to-html
MIT License
20 stars 2 forks source link

block-content-to-html

Render an array of block text from Sanity to HTML.

⚠️ Note: This package is deprecated. We recommend migrating to its modernized successor, @portabletext/to-html.

Installing

npm install --save @sanity/block-content-to-html

Usage

const blocksToHtml = require('@sanity/block-content-to-html')
const client = require('@sanity/client')({
  projectId: '<your project id>',
  dataset: '<some dataset>',
  apiVersion: '2021-03-25',
  useCdn: true
})

// `h` is a way to build HTML known as hyperscript
// See https://github.com/hyperhype/hyperscript for more info
const h = blocksToHtml.h

const serializers = {
  types: {
    code: props => (
      h('pre', {className: props.node.language},
        h('code', props.node.code)
      )
    )
  }
}

client.fetch('*[_type == "article"][0]').then(article => {
  const el = blocksToHtml({
    blocks: article.body,
    serializers: serializers
  })

  document.getElementById('root').appendChild(el)
})

Options

In addition, in order to render images without materializing the asset documents, you should also specify:

Examples

Rendering custom marks

const input = [{
  _type: 'block',
  children: [{
    _key: 'a1ph4',
    _type: 'span',
    marks: ['s0m3k3y'],
    text: 'Sanity'
  }],
  markDefs: [{
    _key: 's0m3k3y',
    _type: 'highlight',
    color: '#E4FC5B'
  }]
}]

const highlight = props => (
  h('span', {style: {backgroundColor: props.mark.color}}, props.children)
)

const content = blocksToHtml({
  blocks: input,
  serializers: {marks: {highlight}}
})

Specifying image options

blocksToHtml({
  blocks: input,
  imageOptions: {w: 320, h: 240, fit: 'max'},
  projectId: 'myprojectid',
  dataset: 'mydataset',
})

Customizing default serializer for block-type

const BlockRenderer = props => {
  const style = props.node.style || 'normal'

  if (/^h\d/.test(style)) {
    const level = style.replace(/[^\d]/g, '')
    return h('h2', {className: `my-heading level-${level}`}, props.children)
  }

  return style === 'blockquote'
    ? h('blockquote', {className: 'my-block-quote'}, props.children)
    : h('p', {className: 'my-paragraph'}, props.children)
}

blocksToHtml({
  blocks: input,
  serializers: {types: {block: BlockRenderer}}
})

License

MIT-licensed. See LICENSE.