Create pages from other md files

This commit is contained in:
LordMathis 2020-10-06 20:51:49 +02:00
parent c064850324
commit 139db50cfd
4 changed files with 71 additions and 6 deletions

View File

@ -23,7 +23,7 @@ module.exports = {
{
resolve: `gatsby-source-filesystem`,
options: {
name: `data`,
name: `pages`,
path: `${__dirname}/content/pages`,
},
},

View File

@ -22,7 +22,8 @@ exports.onCreateNode = ({ node, getNode, actions }) => {
exports.createPages = async ({ graphql, actions, reporter }) => {
const { createPage } = actions
const result = await graphql(
// Posts query
const posts = await graphql(
`
{
allMarkdownRemark(filter:{frontmatter: {draft: {ne: true}}, fields: {collection: {eq: "posts"}}}) {
@ -39,19 +40,51 @@ exports.createPages = async ({ graphql, actions, reporter }) => {
)
// Handle errors
if (result.errors) {
if (posts.errors) {
reporter.panicOnBuild(`Error while running GraphQL query.`)
return
}
// Create pages for each markdown file.
const blogPostTemplate = path.resolve(`src/templates/blog-post.js`)
result.data.allMarkdownRemark.edges.forEach(({ node }) => {
posts.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: `/posts${node.fields.slug}`,
component: blogPostTemplate,
// In your blog post template's graphql query, you can use pagePath
// as a GraphQL variable to query for data from the markdown file.
context: {
slug: node.fields.slug,
},
})
})
const pages = await graphql(
`
{
allMarkdownRemark(filter: {fields: {collection: {eq: "pages"}}}) {
edges {
node {
fields {
slug
}
}
}
}
}
`
)
// Handle errors
if (pages.errors) {
reporter.panicOnBuild(`Error while running GraphQL query.`)
return
}
// Create pages for each markdown file.
const pageTemplate = path.resolve(`src/templates/page.js`)
pages.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.fields.slug,
component: pageTemplate,
context: {
slug: node.fields.slug,
},

View File

@ -0,0 +1,5 @@
@import "./variables.scss";
.pageWrapper {
text-align: left;
}

27
src/templates/page.js Normal file
View File

@ -0,0 +1,27 @@
import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
import styles from "../styles/page.module.scss"
export default function Page({ data }) {
const page = data.markdownRemark
return (
<Layout>
<div className={styles.blogPostWrapper}>
<h1>{page.frontmatter.title}</h1>
<div dangerouslySetInnerHTML={{ __html: page.html }} />
</div>
</Layout>
)
}
export const query = graphql`
query($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
}
}
}
`