【发布时间】:2018-10-18 22:18:37
【问题描述】:
我试图跟上 Gatsby 的速度并在演示中取得了巨大的成功,但我觉得这是一个相对常见且简单的用例。我希望有多种可以在 Markdown 中编写的内容类型,每种都有不同的 Frontmatter,每种都有不同的模板。
例如,我想要一个 BlogPost 内容类型和一个 Project 内容类型:
博文内容类型
---
title: My Post
date: "2017-09-21"
---
This is my blog body
项目内容类型
---
projectName: My Project
startDate: "2017-09-21"
endDate: "2017-10-21"
---
This is my project description
然后为了让它们在相关模板中呈现,我不得不使用正则表达式在gatsby-node.js 中做一些骇人听闻的事情:
const components = {
blog: `./src/templates/blog-post.js`,
projects: `./src/templates/project-post.js`,
}
exports.createPages = ({ graphql, boundActionCreators }) => {
const { createPage } = boundActionCreators
RE_DIR = new RegExp("\/pages\/([a-z]+)\/.*\.md$");
return new Promise((resolve, reject) => {
graphql(`
{
allMarkdownRemark {
edges {
node {
fileAbsolutePath
fields {
slug
}
}
}
}
}
`).then(result => {
result.data.allMarkdownRemark.edges.forEach(({ node }) => {
// console.log(RE_DIR.exec(node.fileAbsolutePath))
const postType = RE_DIR.exec(node.fileAbsolutePath)[1]
if (postType) {
createPage({
path: node.fields.slug,
component: path.resolve(components[postType]),
context: {
// Data passed to context is available in page queries as GraphQL variables.
slug: node.fields.slug,
},
})
}
})
resolve()
})
})
};
我现在遇到的问题是,由于 frontmatter 不一致,看来 GraphQL 仅从其中一个来源获取 frontmatter 模式。
有没有更简单的方法来拥有多种内容类型?
【问题讨论】: