简体   繁体   English

在 Gatsby 中从 graphQL 查询创建 slug

[英]Creating slugs from graphQL query in Gatsby

I am connecting to a database, and this query is showing me the IDs that I want:我正在连接到数据库,此查询向我显示了我想要的 ID:

allSongs {
        edges {
          node {
            id
          }
        }
      }

So now I want to be able to load a dynamic page like this:所以现在我希望能够加载这样的动态页面:
site.com/song/6 site.com/song/6

Where the "6" is the id above.其中“6”是上面的 id。 It looks like I'll need to create slugs dynamically based on the query, but I'm having trouble getting it to work.看起来我需要根据查询动态创建 slug,但我无法让它工作。 Any help appreciated!任何帮助表示赞赏!

You can use createPage api in gatsby-node.js and create dynamic pages您可以在gatsby-node.js中使用createPage api 并创建动态页面

// Create song pages dynamically
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  const songTemplate = path.resolve(`src/templates/songs.js`)
  const result = await graphql(`
    query {
      allSongs {
        edges {
          node {
            id
          }
        }
      }
    }
  `)
  result.data.allSongs.edges.forEach(edge => {
    createPage({
      path: `/song/${edge.node.id}`,
      component: songTemplate,
    })
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM