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

标签 javascript reactjs gatsby

我正在使用 GatsbyJS 构建个人网页。我有多个页面,两个相关的页面是项目/投资组合页面和博客页面。

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

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

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

博客页面从 pages 文件夹中抓取博客文章 markdown 文件并使用博客文章模板显示它们,这工作正常。

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

最佳答案

是的,这完全有可能。

解决方案其实很简单,但需要稍微了解一下 Gatsby 的内部结构才能弄明白。参见 this snippet on GatsbyCentral如果您已经对 Gatsby 有所了解。

否则,这里有更详细的解释。

在您的 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"}}}) {
  ...

希望对您有所帮助。

关于javascript - Gatsby JS - 多个页面拉入不同类别的 Markdown 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51578264/

相关文章:

javascript - 为什么在运行我的 Gatsby 开发服务器时会遇到这些错误?

javascript - 如何修复控制台警告 "The resource ... was preloaded using link preload but not used within a few seconds from the window' s 加载事件”?

javascript - 多个按钮仅在代码中打开最近的模态

javascript - 使用交互式帖子在 google+ 上发布图片

javascript - react 中单个按钮上的两个事件

javascript - 未捕获的不变违规 : Objects are not valid as a React child

html - 有没有办法在卡片内的 Material-UI Typography 元素中加粗一个词,而无需渲染?

javascript - 组件内部方法的调用由根来回答

javascript - 通知主页面外部js改变的变量

gatsby - 如何使用 React-three-fiber 添加 Stats.js 到 Gatsby 站点?