【问题标题】:How do I create multiple pages from a single markdown file?如何从单个 Markdown 文件创建多个页面?
【发布时间】:2021-02-25 06:06:10
【问题描述】:

在 Gatsby 中,我有 file.md,我想生成多个页面——file.md 的每个部分一个页面。

gatsby-transformer-remark

使用gatsby-transformer-remark 时,我可以使用allMarkdownRemark.nodes.html 获取整个markdown 文件的HTML。如何获取文件每个部分的 HTML?例如:

file.md:

# section 1

**bold**

# section 2

foo

我想获得一组 HTML 部分,例如:

[
  '<div><h1>section 1</h1><b>bold</b></div>', 
  '<div><h1>section 2</h1>foo</div>'
]

gatsby-plugin-mdx

有了gatsby-plugin-mdx,我什么时候做

query MyQuery {
  mdx {
    headings {
      value
      depth
    }
  }
}

我明白了

{
  "data": {
    "mdx": {
      "headings": [
        {
          "value": "Section1",
          "depth": 1
        },
        {
          "value": "Section2",
          "depth": 1
        },
      ]
    }
  },
  "extensions": {}
}

但是当我这样做时:

query MyQuery {
  mdx(headings: {elemMatch: {value: {eq: "Section1"}}}) {
    body
  }
}

body 是整个文件,而不仅仅是 Section1。

【问题讨论】:

    标签: markdown gatsby gatsby-plugin


    【解决方案1】:

    在您的降价文件中,file.md 之后的所有内容都位于--- 之后是降价的主体,您可以直接获取其中的一部分。

    我会建议使用 MDX (Markdown + JSX) 的不同解决方法,它允许您将 React 的逻辑添加到降价文件。 Gatsby 有一个详细的插件:https://www.gatsbyjs.com/plugins/gatsby-plugin-mdx/

    不使用 MDX 的另一种解决方法是在降价中使用“部分”。比如这样的结构:

    ---
    title: Test
    section1:
      description: some description 
    section2:
        title: Some **bold title** for the section 2
    ---
    The rest of the body content
    

    将为每个部分创建一个节点,因此您的对象将分别类似于allMarkdownRemark.nodes.section1.descriptionallMarkdownRemark.nodes.section2.title

    请注意,您可以添加所有支持 Markdown 的样式。

    【讨论】:

    • 谢谢,实际部分很长,所以不适合在frontmatter中缩进。我尝试了您的 gatsby-plugin-mdx 建议,但没有看到如何分别获取每个部分的内容。你知道如何?我用我的进度编辑了问题。
    • MDX 的主体实际上是一个 JSX 文件,所以添加您的组件并根据需要包装内容。
    • 我不确定添加组件如何使我能够从单个 mdx 文件生成多个页面?
    • 不,在 MDX 文件中添加组件将允许您自定义 Markdown 正文的部分
    • 好的,所以听起来使用gatsby-plugin-mdx 不是我原来问题的解决方案。
    猜你喜欢
    • 2023-03-17
    • 2023-04-02
    • 1970-01-01
    • 2020-02-25
    • 2014-07-20
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多