22moonriver
22moonriver

Reputation: 109

Does Gatsby's createPages API send the path to the template?

I've been following this Gatsby tutorial to create pages dynamically based on my CMS's creation of markdown files: https://www.gatsbyjs.org/docs/adding-markdown-pages/

I don't understand how the GraphQL query in the file blogTemplate.js receives the $path variable. I can see that the createPages function in gatsby-node.js creates the page based off the result of its own GraphQL query, and uses the 'path' frontmatter element to choose the URL for the created page.

However, how does that created page know its own path? The query called pageQuery in the tutorial uses the $path variable to source its own data, but I can't see how it receives that variable. Thank you in advance for any explanation.

Upvotes: 0

Views: 688

Answers (2)

Gilbish Kosma
Gilbish Kosma

Reputation: 887

While creating the pages, we can pass context, All context values are made available to a template’s GraphQL queries as arguments prefaced with $

     exports.createPages = async function ({ actions, graphql }) {
  const { data } = await graphql(`
    query {
      allMarkdownRemark {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
  `)
  data.allMarkdownRemark.edges.forEach(edge => {
    const slug = edge.node.fields.slug
    actions.createPage({
      path: slug,
      component: require.resolve(`./src/templates/blog-post.js`),
      context: { path: slug }, //here you can pass path through context parameter, the slug can be then accesed under $path variable in the template
    })
  })
}
`

using $ sign we can then access the path value in template side

  export const query = graphql`
  query($path: String!) {
    ...
  }
`

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281636

Graphql uses redux internall and all information regarding pages creation and paths are updated to gatsby's redux store and from thereon the graphql query is executed for each page

Now according to gatsby createPage github code comment

Data in "context" is passed to GraphQL as potential arguments when running the page query.

When arguments for GraphQL are constructed, the context object is combined with the page object so both page object and context data are available as arguments. So you don't need to add the page "path" to the context as it's already available in GraphQL. If a context field duplicates a field already used by the page object, this can break functionality within Gatsby so must be avoided.

Upvotes: 0

Related Questions