问题描述
我的索引页显示带有图像和文本的简介。
但我无法将文本格式化为 HTML。我将 markdown-widget 与 Netlify CMS 一起使用,并希望在管理视图中分隔内容时可以使用换行符。
我也试过使用 dangerouslySetInnerHTML={item.text}
也没有任何运气。
item 只是所有信息的映射。
<p> {item.text} </p>
graphql:
markdownRemark(frontmatter: { templateKey: { eq: "index-page" } }) {
frontmatter {
intro {
blurbs {
image {
childImageSharp {
fluid(maxWidth: 2048,quality: 100) {
...GatsbyImageSharpFluid
}
}
}
heading
text
}
heading
description
}
}
}
}
- {label: "Intro",name: "intro",widget: "object",fields: [{label: "heading",name: "heading",widget: "string"},{label: "Description",name: "description",widget: text},{label: Blurbs,name: blurbs,widget: "list",fields: [{label: "Image",name: "image",widget: "image"},{label: "Rubrik",{label: "Text",name: "text",widget: "markdown"}]}]}
我想从中读取的 Index.md(我想这是可行的,因为我要显示数据,只是不是以 html 形式)
blurbs:
- image: /img/img1.jpg
heading: heading one
text: >-
This is the content i want in HTML
- image: /img/img2.jpg
heading: heading two
text: >-
This is also the content i want in HTML
And this should give me a linebreak
解决方法
您可以使用 gatsby-transformer-remark-frontmatter 插件实现这一点。
安装插件并将其添加到 gatsby-config.js 中:
$ npm install gatsby-transformer-remark-frontmatter
// in your gatsby-config.js
plugins: [
'gatsby-transformer-remark','gatsby-transformer-remark-frontmatter'
]
要告诉 Gatsby 每个简介中的文本字段包含 markdown 并且您希望将字符串转换为 html,您需要向架构添加 @md 指令。为此,请将以下代码添加到 gatsby-node.js
文件中。
// in your gatsby-node.js
exports.createSchemaCustomization = ({ actions }) => {
const {createTypes} = actions
const typeDefs = `
type MarkdownRemark implements Node {
frontmatter: Frontmatter
}
type Frontmatter {
intro: Intro
}
type Intro {
blurbs: [Blurb]
}
type Blurb {
text: String @md
}
`
createTypes(typeDefs)
}
现在,简介的 text
字段将有一个特殊的 html
字段,您可以将其包含在查询中:
markdownRemark(frontmatter: { templateKey: { eq: "index-page" } }) {
frontmatter {
intro {
blurbs {
text {
html
}
}
}
}
}
}
最后,在您的组件中,您应该能够像这样循环播放简介并渲染 html:
...
<div dangerouslySetInnerHTML={{ __html: blurb.text.html }} />
,
假设一切都设置正确,就像看起来的那样。
默认情况下,html
中有一个 frontmatter
属性:
markdownRemark(frontmatter: { templateKey: { eq: "index-page" } }) {
frontmatter {
html
intro {
blurbs {
image {
childImageSharp {
fluid(maxWidth: 2048,quality: 100) {
...GatsbyImageSharpFluid
}
}
}
heading
text
}
}
}
}
}
注意:在 localhost:8000/___graphql
一旦你查询了它,就像你所做的那样显示它,嵌套到正确的属性:
dangerouslySetInnerHTML={html}
您可以在 https://www.gatsbyjs.com/docs/how-to/sourcing-data/sourcing-from-netlify-cms/
查看完整教程