Dmitry Samoylenko
Dmitry Samoylenko

Reputation: 13

How to define Gatsby markdown page paths in one file?

Bu default, Gatsby uses frontmatter for defining paths, like:

---
path: /example-page
---

and then works with it via GraphQL.

What is the best way to define those paths for all markdown files by not writing frontmatter part in every file, but in one file, as an instance, like this:

[
    {
        "title": "Example",
        "path": "/example-page.md"
    }
]

Upvotes: 0

Views: 1035

Answers (1)

anthowelc
anthowelc

Reputation: 85

You can do that by adding the path when the page is created.

Add this in gatsby-node :

const { createFilePath } = require(`gatsby-source-filesystem`);

exports.onCreateNode = ({ node, getNode, boundActionCreators }) => {

  const { createNodeField } = boundActionCreators

  if (node.internal.type === `MarkdownRemark`) {

    const slug = createFilePath({
      node,
      getNode,
      basePath: `pages`
    })

    createNodeField({
      node,
      name: `slug`,
      value: `/pages${slug}`
    })

  }

};

createFilePath turn markdown files in pages directory into /pages/slug.

createNodeField creates new query'able field with name of 'slug'.

Now in graphql you can access the slug :

{
  allMarkdownRemark {
    edges {
      node {
        fields {
          slug
        }
      }
    }
  }
}

Then you can create your pages as usual using the new slug field as page path.

With that you can add your title and all you want in data accessible in graphql.

Example here : https://www.gatsbyjs.org/tutorial/part-seven/

Upvotes: 2

Related Questions