Skip to content

Instantly share code, notes, and snippets.

@kmelve
Created June 26, 2018 14:42
Show Gist options
  • Select an option

  • Save kmelve/b9bda5c9e971196a8b8a6217d816038c to your computer and use it in GitHub Desktop.

Select an option

Save kmelve/b9bda5c9e971196a8b8a6217d816038c to your computer and use it in GitHub Desktop.
Block Content To Hyperscript implementation for Vue
<template>
<div class="content">
<div v-html="renderHtml(indexedContent)"></div>
</div>
</template>
<script>
/**
*** Run block content from Sanity through serializers
**/
/* eslint-disable */
const blocksToHtml = require("@sanity/block-content-to-html");
const h = require("hyperscript");
import client from "@/helpers/client";
import imageUrlBuilder from "@sanity/image-url";
const builder = imageUrlBuilder(client);
const urlFor = source => builder.image(source);
const urlResolver = (link = "") => {
if (link.hasOwnProperty("current")) {
return `/${link.current}`;
}
if (link.hasOwnProperty("link")) {
return `/${link.link.current}`;
} else if (link.hasOwnProperty("external")) {
return link.external;
}
};
const serializers = {
marks: {
link: ({ mark: { href = "", internal = "" } = {}, children = [] }) => {
return h("a", {
className: "link",
href: href ? href : `/${internal}`
}, children);
},
strong: ({ children}) => (
h('strong', children)
),
normal: ({children}) => (
h('span', children)
)
},
types: {
image: ({ node: { image = '', position = 'full', caption = '' } = {} }) => {
if (caption) {
return h('div', { className: position },
h('img', { src: image}),
h('p', { className: 'caption', textContent: caption})
)
}
return image && h('img', { src: image, className: position })
},
block: (props) => {
const style = props.node.style || 'normal'
if (/^h\d/.test(style)) {
const level = style.replace(/[^\d]/g, '')
return h(`h${level}`, {}, props.children)
}
return h('p', props.children)
},
children: ({ node: { textBlockArray = [] } }) =>
h(
"div",
{ className: "textblock" },
textBlockArray.length
? textBlockArray.map(item =>
h("div", {
className: "textblock__content",
innerHTML: blocksToHtml({ blocks: item, serializers })
})
)
: null
)
}
};
export default {
name: "BlockContentToVue",
props: ["content"],
methods: {
renderHtml(blocks = []) {
return blocksToHtml({
blocks: blocks,
serializers: serializers,
projectId: client.clientConfig.projectId,
dataset: client.clientConfig.dataset
})
}
}
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment