Skip to content

Instantly share code, notes, and snippets.

@danilowoz
Created April 28, 2019 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danilowoz/75a7d1f62b719085dda4407f18fc7119 to your computer and use it in GitHub Desktop.
Save danilowoz/75a7d1f62b719085dda4407f18fc7119 to your computer and use it in GitHub Desktop.
Creating the pages programmatically
const path = require(`path`)
// 1. This is called once the data layer is bootstrapped to let plugins create pages from data.
exports.createPages = ({ graphql, actions }) => {
// 1.1 Getting the method to create pages
const { createPage } = actions
// 1.2 Tell which layout Gatsby should use to thse pages
const blogLayout = path.resolve(`./src/layouts/blog-post.js`)
// 2 Return the method with the query
return graphql(`
query blogPosts {
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
edges {
node {
fields {
slug
}
frontmatter {
title
date
author
category
tags
featured
}
html
}
}
}
}
`).then(result => {
// 2.1 Handle the errors
if (result.errors) {
console.error(result.errors)
reject(result.errors)
}
// 2.2 Our posts are here
const posts = result.data.allMarkdownRemark.edges
// 3 Loop throught all posts
posts.forEach((post, index) => {
// 3.1 Finally create posts
createPage({
path: post.node.fields.slug,
component: blogLayout,
context: {
slug: post.node.fields.slug,
},
})
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment