是的,这是完全可能的。
解决方案其实很简单,但是需要稍微了解一下盖茨比的内部原理才能弄清楚。如果您对 Gatsby 有所了解,请参阅 this snippet on GatsbyCentral。
否则,这里有一个更详细的解释。
在您的gatsby-node.js 文件中,您需要添加以下代码:
exports.onCreateNode = ({ node, boundActionCreators, getNode }) => {
const { createNodeField } = boundActionCreators;
if (_.get(node, "internal.type") === `MarkdownRemark`) {
// Get the parent node
const parent = getNode(_.get(node, "parent"));
// Create a field on this node for the "collection" of the parent
// NOTE: This is necessary so we can filter `allMarkdownRemark` by
// `collection` otherwise there is no way to filter for only markdown
// documents of type `post`.
createNodeField({
node,
name: "collection",
value: _.get(parent, "sourceInstanceName")
});
}
};
确保您还拥有 lodash 所需的 require() 语句:
const _ = require("lodash")
现在确保您在 gatsby-config.js 中有两个插件部分,用于博客文章和项目。确保每个人都有一个name 选项,例如:
plugins: [
{
resolve: "gatsby-source-filesystem",
options: {
name: "pages",
path: `${__dirname}/src/pages`
}
},
{
resolve: "gatsby-source-filesystem",
options: {
name: "projects",
path: `${__dirname}/src/projects`
}
},
然后您可以查询allMarkdownRemark 集合并过滤字段collection。它将是pages 或projects。
示例查询可能如下所示:
query {
allMarkdownRemark(filter: {fields: {collection: {eq: "pages"}}}) {
...
希望对您有所帮助。