Gatsby JS - 多个页面拉入不同类别的降价文件

Gatsby JS - Multiple pages pulling in markdown files with different categorys

我正在使用 GatsbyJS 构建个人网页。我有多个页面,两个相关的页面是 projects/portfolio 页面和博客页面。

我在博客页面上设置了 gatsby,它从特定文件夹中提取降价文件,并使用博客页面上的模板显示它们。我想在 projects/portfolio 页面上以类似的方式展示我的项目。 我的文件夹结构如下:

-src
 -pages
  -BlogPostOne
  -BlogPostTwo
  projects.js
  blog.js
 -templates
  BlogPostTemplate.js
  ProjectTemplate.js
 -projects
  -project1
  -project2

我希望项目页面从项目文件夹中抓取项目降价文件并使用项目模板显示它们

博客页面从 pages 文件夹中抓取博客 post markdown 文件并使用博客 post 模板显示它们,这很好。

我基本上使用了与获取博客 post 具有不同变量名称和路径的文件相同的代码,但它不起作用。盖茨比甚至可以做到这一点吗?我搜索了他们的文档,但找不到与我正在尝试做的类似的内容。有没有人有用盖茨比做类似事情的经验?

是的,这完全有可能。

解决方案其实很简单,但需要稍微了解一下Gatsby的内部结构才能弄明白。如果您已经对 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。它将是 pagesprojects.

示例查询可能如下所示:

query {
  allMarkdownRemark(filter: {fields: {collection: {eq: "pages"}}}) {
  ...

希望对您有所帮助。