从 Gatsby NetlifyCMS 项目中的 frontmatter 渲染 markdown/HTML

Render markdown/HTML from frontmatter in a Gatsby NetlifyCMS project

NetlifyCMS 提供了一个 markdown 编辑器,允许在 frontmatter 中插入 markdown(和代码块)。

生成的降价文件可能包含如下内容:

---
featureSubtitle: |-
  ![fdsaf](/img/cdc-w9keokhajkw-unsplash.jpg "blah")

  # Markdown H1

  ## Markdown H2


  <h1>Test</h1>
  <p>Paragraph</p>
---

然后通过 graphql 查询将其从 frontmatter 加载到页面上:

export const pageQuery = graphql`
  query FeaturePageByID($id: String!) {
    markdownRemark(id: { eq: $id }) {
      id
      html
      frontmatter {
        title
        description
        featureSubtitle
      }
    }
  }
`;

{featureSubtitle && featureSubtitle ? (
                  <div
                    dangerouslySetInnerHTML={{ __html: featureSubtitle }}
                  />
                ) : null}

然而,这似乎正确地呈现了 HTML,但不是降价。

gatsby transformer remark plugin does convert markdown to html in the body of your markdown file and gets the frontmatter data at the top of your markdown file. The frontmatter is used mainly for metadata. You can however convert the frontmatter field yourself to html. See this link。

或者确保在 netlify cms 的 config.yml 中像这样使用正文作为 markdown 字段:

fields:
      - { label: "featureSubtitle", name: "body", widget: "markdown" }

然后可以使用 graphql 查询中的 html 字段将其检索为 html 并像这样使用:

<div dangerouslySetInnerHTML={{ __html: html}} />