Programmatically create Gatsby pages from Contentful data

与世无争的帅哥 提交于 2019-12-05 07:42:12

You can create pages dynamically at build time and to do that you need to add some logic to the gatsby-node.js file. Here is a simple snippet.

const path = require('path')

exports.createPages = ({graphql, boundActionCreators}) => {
  const {createPage} = boundActionCreators
  return new Promise((resolve, reject) => {
    const storeTemplate = path.resolve('src/templates/store.js')
    resolve(
      graphql(`
        {
          allContentfulStore (limit:100) {
            edges {
              node {
                id
                name
                slug
              }
            }
          }
        }
      `).then((result) => {
        if (result.errors) {
          reject(result.errors)
        }
        result.data.allContentfulStore.edges.forEach((edge) => {
          createPage ({
            path: edge.node.slug,
            component: storeTemplate,
            context: {
              slug: edge.node.slug
            }
          })
        })
        return
      })
    )
  })
}

the createPages that was exported is a Gatsby Node API function you can find the complete list in the docs here.

For the query allContentfulStore it's called like that because your contentType name is store the gatsby query will be allContentful{ContentTypeName}.

Finally, I created a youtube video series explaining how you can build a Gatsby website with Contentful. You can find it here

I hope this answer your question. Cheers, Khaled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!