Created
April 28, 2019 19:12
-
-
Save danilowoz/75a7d1f62b719085dda4407f18fc7119 to your computer and use it in GitHub Desktop.
Creating the pages programmatically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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