使用Gatsby将Richdown文本组件中的Markdown转换为HTML [英] Convert Markdown to HTML from within a Rich-Text Component with Gatsby
问题描述
我正在使用Contentful的富文本字段类型来构建页面,我拥有的Embedded_Blocks之一是我正在用来构建表的Markdown字段类型:
I am using Contentful's Rich-Text Field type to build pages, one of the Embedded_Blocks I have is for a Markdown field type which I am using to build a table:
降价字段类型:
| Title | Title |
| ---------- | ---------- |
| Cell | Cell |
我可以检索Rich-Text数据并像这样构建我的Embedded_Blocks:
I can retrieve the Rich-Text data and build out my Embedded_Blocks like this:
[BLOCKS.EMBEDDED_ENTRY]: (node) => {
const fields = node.data.target.fields;
switch (node.data.target.sys.contentType.sys.id) {
case 'video':
const url = (fields.url['en-US']);
return <Video url={url}/>
// This is how I'm currently trying to convert Markdown to HTML
///////////////////////////////////////////////////////////////
case 'markdown':
const markdown = (fields.markdown['en-US']);
console.log('markdown', markdown);
return <div dangerouslySetInnerHTML={{ __html: markdown }} />
default:
return <div>Fallback</div>
}
},
我遇到的问题是,它只是返回一个字符串,我假设这是因为在将markdown
传递给dangerouslySetInnerHTML={{ __html: markdown }}
之前,我还没有将markdown
转换为HTML.
The problem I have with this is that it just returns a string, I'm assuming because I have not converted markdown
to HTML before passing it to dangerouslySetInnerHTML={{ __html: markdown }}
.
如何将Markdown转换为HTML,以便可以使用dangerouslySetInnerHTML={{ __html: markdown }}
呈现它?
How can I convent the Markdown to HTML so that I can render it using dangerouslySetInnerHTML={{ __html: markdown }}
?
推荐答案
The most appropriate way to do this inside of Gatsby would be to create child nodes inside of the Gatsby onCreateNode
lifecycle hook. This hook is only called in the nodejs process, and runs the markdown parsing once when the Contentful entry is downloaded.
This should get you started - it's based on the code inside of Gatsby's gatsby-transformer-remark
请注意,这是伪代码-当然,您必须对其进行测试.
Note that this is pseudocode - you'll have to of course test it.
// gatsby-node.js
var remark = require('remark')
var recommended = require('remark-preset-lint-recommended')
var html = require('remark-html')
const processor = remark()
.use(recommended)
.use(html)
export async function onCreateNode({ actions, node, loadNodeContent}) {
if (!/RichText/.test(node.internal.type)) {
return
}
const markdown = // somehow load the raw markdown from the node - I haven't studied RichText nodes yet
const html = processor.process(markdown)
const markdownNode = {
id: createNodeId(`${node.id} >>> MarkdownRemark`),
children: [],
parent: node.id,
internal: {
content: data.content,
type: `MarkdownRemark`,
},
}
actions.createNode(markdownNode)
actions.createParentChildLink({ parent: node, child: markdownNode })
}
作为参考,这是Contentful在盖茨比内部创建RTF节点的地方:
这篇关于使用Gatsby将Richdown文本组件中的Markdown转换为HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!