Graphql 如何在一个文件中定义盖茨比标记页路径?
Bu默认值,用于定义路径,如:Graphql 如何在一个文件中定义盖茨比标记页路径?,graphql,gatsby,static-site,Graphql,Gatsby,Static Site,Bu默认值,用于定义路径,如: --- path: /example-page --- 然后通过GraphQL使用它 通过不在每个文件中写入frontmatter部分,而是在一个文件中写入frontmatter部分来定义所有标记文件的路径的最佳方法是什么,例如: [ { "title": "Example", "path": "/example-page.md" } ] 您可以通过在创建页面时添加路径来实现这一点 将此添加到盖茨比节点中: co
---
path: /example-page
---
然后通过GraphQL使用它
通过不在每个文件中写入frontmatter部分,而是在一个文件中写入frontmatter部分来定义所有标记文件的路径的最佳方法是什么,例如:
[
{
"title": "Example",
"path": "/example-page.md"
}
]
您可以通过在创建页面时添加路径来实现这一点 将此添加到盖茨比节点中:
const { createFilePath } = require(`gatsby-source-filesystem`);
exports.onCreateNode = ({ node, getNode, boundActionCreators }) => {
const { createNodeField } = boundActionCreators
if (node.internal.type === `MarkdownRemark`) {
const slug = createFilePath({
node,
getNode,
basePath: `pages`
})
createNodeField({
node,
name: `slug`,
value: `/pages${slug}`
})
}
};
createFilePath
将pages
目录中的标记文件转换为/pages/slug
createNodeField
创建名为“slug”的新可查询字段
现在,在graphql
中,您可以访问slug:
{
allMarkdownRemark {
edges {
node {
fields {
slug
}
}
}
}
}
然后,您可以像往常一样使用新的slug字段作为页面路径来创建页面
有了它,您可以在graphql中访问的数据中添加标题和所有需要的内容
这里的示例:您可以通过在创建页面时添加路径来实现 将此添加到盖茨比节点中:
const { createFilePath } = require(`gatsby-source-filesystem`);
exports.onCreateNode = ({ node, getNode, boundActionCreators }) => {
const { createNodeField } = boundActionCreators
if (node.internal.type === `MarkdownRemark`) {
const slug = createFilePath({
node,
getNode,
basePath: `pages`
})
createNodeField({
node,
name: `slug`,
value: `/pages${slug}`
})
}
};
createFilePath
将pages
目录中的标记文件转换为/pages/slug
createNodeField
创建名为“slug”的新可查询字段
现在,在graphql
中,您可以访问slug:
{
allMarkdownRemark {
edges {
node {
fields {
slug
}
}
}
}
}
然后,您可以像往常一样使用新的slug字段作为页面路径来创建页面
有了它,您可以在graphql中访问的数据中添加标题和所有需要的内容
示例如下: