javascript - 盖茨比第二版布局模板
问题描述
我有一个我创建的模板,它用于显示单个产品(blog-post.js)的页面。现在我需要一种带有自己模板(category-post.js)的新型页面,它将显示某个类别中的所有产品。我不知道会有多少类别,所以我需要它们是动态的(以编程方式创建)。
为此,我认为我应该使用 onCreatePage API。在我添加 onCreatePage 函数之前,代码运行良好。
我是按照www.gatsbyjs.org 上的这些文档来选择页面布局的。我希望我至少在正确的轨道上。
gatsby-node.js,问题似乎在这里:
exports.createPages = ({ graphql, boundActionCreators }) => {
const { createPage } = boundActionCreators
return new Promise((resolve, reject) => {
const blogPost = path.resolve('./src/templates/blog-post.js')
resolve(
graphql(
`
{
allContentfulBlog(limit: 200) {
edges {
node {
id
categories
slug
}
}
}
}
`
).then(result => {
if (result.errors) {
console.log(result.errors)
reject(result.errors)
}
result.data.allContentfulBlog.edges.forEach(edge => {
createPage({
path: edge.node.slug,
component: blogPost,
context: {
slug: edge.node.slug,
},
})
})
return
})
)
})
}
exports.onCreatePage = async ({ page, boundActionCreators }) => {
const { createPage } = boundActionCreators
return new Promise((resolve, reject) => {
if (page.path.match(/^\/category-post/)) {
// I have created `category-post.js` in the `/layouts/` directory
page.layout = 'category-post'
createPage(page)
}
resolve()
})
}
我还可以指定我正在使用 Contentful CMS,这可以通过那里的一些 API 以某种方式完成吗?
有人做过类似的事情并想提供帮助吗?
解决方案
to create pages dynamically you still need to use the createPages API. One thing that people miss is that you can have as much GraphQL query as you want.
the onCreatePage
is unnecessary in this case because you were looking for pages that are not created
exports.createPages = ({ graphql, boundActionCreators }) => {
const { createPage } = boundActionCreators
return new Promise((resolve, reject) => {
const blogPost = path.resolve('./src/templates/blog-post.js')
const categoryPost = path.resolve('./src/templates/category-post.js')
resolve(
graphql(
`
{
allContentfulBlog(limit: 200) {
edges {
node {
id
categories
slug
}
}
}
allContentfulCategory(limit: 200) {
edges {
node {
id
categories
slug
}
}
}
}
`
).then(result => {
if (result.errors) {
console.log(result.errors)
reject(result.errors)
}
result.data.allContentfulCategory.edges.forEach(edge => {
createPage({
path: `categories/${edge.node.slug}`,
component: categoryPost,
context: {
slug: edge.node.slug,
},
})
})
result.data.allContentfulBlog.edges.forEach(edge => {
createPage({
path: edge.node.slug,
component: blogPost,
context: {
slug: edge.node.slug,
},
})
})
return
})
)
})
}