How do I create multiple pages from a single markdown file?

Viewed 621

In Gatsby, I have file.md, and I'd like to generate multiple pages—one for each section of file.md.

gatsby-transformer-remark

When using gatsby-transformer-remark, I can get the HTML of an entire markdown file with allMarkdownRemark.nodes.html. How do I get the HTML of each section of the file? For instance:

file.md:

# section 1

**bold**

# section 2

foo

I'd like to get an array of section HTMLs, like:

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

gatsby-plugin-mdx

With gatsby-plugin-mdx, when do I

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

I get

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

But when I do:

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

The body is the entire file, not just Section1.

1 Answers

In your markdown file, the file.md everything that is after the --- is the body of the markdown so directly, you can get parts of it.

I would suggest a different workaround using MDX (Markdown + JSX) which allows you to add React's logic inside a markdown file. Gatsby has a detailed plugin for that: https://www.gatsbyjs.com/plugins/gatsby-plugin-mdx/

Another workaround, without using the MDX would be using "sections" inside the markdown. For example, a structure like:

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

Will create a node for each section, so your object will look like allMarkdownRemark.nodes.section1.description and allMarkdownRemark.nodes.section2.title respectively.

Note that you can add all the markdown supported styling along with it.

Related