我正在使用GatsbyJS建立一个个人网页。我有多个页面,两个相关的页面是一个项目/投资组合页面和一个博客页面。
我已经在博客页面上设置了gatsby,它从特定的文件夹中拉入标记文件,并在博客页面上使用模板显示它们。我想在projects/portfolio页面上以类似的方式展示我的项目。我的文件夹结构如下:
-src
-pages
-BlogPostOne
-BlogPostTwo
projects.js
blog.js
-templates
BlogPostTemplate.js
ProjectTemplate.js
-projects
-project1
-project2我希望项目页面从项目文件夹中获取项目标记文件,并使用项目模板显示它们
博客页面从pages文件夹中抓取博客帖子标记文件,并使用博客帖子模板显示它们,这很好用。
我基本上使用了与抓取具有不同变量名和路径的博客文章文件相同的代码,但它不起作用。有没有可能用Gatsby做到这一点?我已经搜索了他们的文档,但找不到任何与我想要做的事情相似的东西。有没有人有使用Gatsby做类似事情的经验?
发布于 2018-08-01 22:19:47
是的,这是完全有可能的。
解决方案实际上非常简单,但需要对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。它将是pages或projects。
示例查询可能如下所示:
query {
allMarkdownRemark(filter: {fields: {collection: {eq: "pages"}}}) {
...希望这对你有帮助。
https://stackoverflow.com/questions/51578264
复制相似问题