Created
July 17, 2020 14:09
-
-
Save onefriendaday/a739bb06cb6c73e4ff486fce207421d1 to your computer and use it in GitHub Desktop.
Richtext renderer with custom schema to add classes directly to headlines
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 RichTextResolver = require('storyblok-js-client/dist/richTextResolver') | |
const MySchema = require('storyblok-js-client/dist/schema') | |
MySchema.nodes.heading = function(node) { | |
let attrs = {} | |
if (node.content && | |
node.content.length === 1 && | |
node.content[0].marks && | |
node.content[0].marks.length === 1 && | |
node.content[0].marks[0].type === 'styled') { | |
attrs = node.content[0].marks[0].attrs | |
delete node.content[0].marks | |
} | |
return { | |
tag: [{ | |
tag: `h${node.attrs.level}`, | |
attrs: attrs | |
}] | |
} | |
} | |
let rteResolver = new RichTextResolver(MySchema) | |
let rendered = rteResolver.render({ | |
"content": [ | |
{ | |
"content": [ | |
{ | |
"text": "Normal headline", | |
"type": "text" | |
} | |
], | |
"type": "paragraph" | |
}, | |
{ | |
"attrs": { | |
"level": 3 | |
}, | |
"content": [ | |
{ | |
"marks": [ | |
{ | |
"attrs": { | |
"class": "margin-bottom-fdsafdsada" | |
}, | |
"type": "styled" | |
} | |
], | |
"text": "Styled headline", | |
"type": "text" | |
} | |
], | |
"type": "heading" | |
} | |
], | |
"type": "doc" | |
}) | |
console.log(rendered) | |
// Returns <p>Normal headline</p><h3 class="margin-bottom-fdsafdsada">Styled headline</h3> instead of <p>Normal headline</p><h3><span class="margin-bottom-fdsafdsada">Styled headline</span></h3> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment