我是 gatsby 的新手,并尝试使用不同的模板以编程方式创建页面,但我正在为此苦苦挣扎。
这是我的 gatsby 节点文件,它可以很好地创建团队成员页面,但是当我想使用位于同一文件夹/templates 的新模板创建博客文章时,就会出现问题
const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const slug = createFilePath({ node, getNode, basePath: `pages` })
createNodeField({
node,
name: `slug`,
value: slug,
})
}
}
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const result = await graphql(`
query {
allMarkdownRemark {
edges {
node {
fields {
slug
}
}
}
}
}
`)
result.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.fields.slug,
component: path.resolve(`./src/templates/member-info.js`),
context: {
slug: node.fields.slug,
},
})
})
}
我尝试了不同的方法,但无法找到解决方案。 谢谢!
最佳答案
最简单的方法是使用不同的模板组件调用createPage
。更可靠的方法可能是在 frontmatter 中定义模板名称并使用它来动态构造相应组件的路径,如下所示:
// some markdown file
---
template: member-info
---
// gatsby-node.js
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const result = await graphql(`
query {
allMarkdownRemark {
edges {
node {
frontmatter {
template
}
fields {
slug
}
}
}
}
}
`)
result.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.fields.slug,
component: path.resolve(`./src/templates/${template}.js`),
context: {
slug: node.fields.slug,
},
})
})
}
关于javascript - 使用不同的模板在 gatsby 中创建页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59270438/