Create posts at different folder

Asked by At

Hi I'm using Gatsby starter blog.

I have two pages - blog and projects. Right now I have six posts, five blog posts and one project post. All the posts including the project post are created under /blog page. How do I ensure projects posts are created in /projects page instead?

I have added gatsby-source-filesystem with the path ${__dirname}/content/projects into my gatsby-config.js already.

Gatsby-node.js

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

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions

  if (node.internal.type === `MarkdownRemark`) {
    const fileNode = getNode(node.parent);
    const value = createFilePath({ node, getNode })

    const parent = fileNode.sourceInstanceName;
    let basePath = (parent === `blog`) ? `blog` : `projects`

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

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions

  const blogPost = path.resolve(`./src/templates/blog-post.js`)
  const projectPost = path.resolve(`./src/templates/project-post.js`)
  return graphql(
    `
      {
        allMarkdownRemark(
          sort: { fields: [frontmatter___date], order: DESC }
          limit: 1000
        ) {
          edges {
            node {
              fields {
                slug
              }
              frontmatter {
                title
              }
            }
          }
        }
      }
    `
  ).then(result => {
    console.log(JSON.stringify(result, null, 4));

    if (result.errors) {
      throw result.errors
    }

    // Create blog and projects posts.
    const posts = result.data.allMarkdownRemark.edges
    posts.forEach((post, index) => {
      const slug = post.node.fields.slug;

      createPage({
        path: `/${slug}`,
        component: blogPost,
        context: {
          slug,
        },
      })
    })

    return null
  })
}

0 Answers