gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:22:14 26 4
gpt4 key购买 nike

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com