Programatically creating pages in Gatsby using Json

Viewed 66

I am using gatsby to programatically create pages but I want to do so at 2 different paths covers/{json.name}.js and styles/{json.name}.js. I have it set up currently working using the gatsby-node.js file but would prefer to have them implemented using the {} convention. Currently getting all my nodes at both paths when trying the {}.js method I am under the impression filtering is impossible using this method but is there currently a work around to get it working with the above method.

1 Answers

Exactly, you hit the nail. Actually, using filters/custom variables is not possible using File System Route API. As you can see in the article feature announcement:

Can I use custom variables for the file name?

Defining custom variables/fields inside the file isn’t possible at the moment, e.g. if you want to use {something}.js for your file name and then define something as MarkdownRemark.fields__slug. Therefore you’ll have to follow the syntax of {Model.field__nestedField}.

There's a lack of specifications in your question so I don't know if the aliasing method will fit you (I guess it doesn't). Aliasing allows you to use multiple gatsbyPath like:

import React from "react"
import { Link, graphql } from "gatsby"

export default function HomePage(props) {
  return (
    <ul>
      {props.data.allProduct.map(product => (
        <li key={product.name}>
          <Link to={product.productPath}>{product.name}</Link> (
          <Link to={product.discountPath}>Discount</Link>)
        </li>
      ))}
    </ul>
  )
}

export const query = graphql`
  query {
    allProduct {
      name
      productPath: gatsbyPath(filePath: "/products/{Product.name}")
      discountPath: gatsbyPath(filePath: "/discounts/{Product.name}")
    }
  }
`

If it doesn't fit you, you won't be able to get rid of the gatsby-node.js so the filesystem API won't be a valid option.

Related