【发布时间】:2020-04-03 16:32:55
【问题描述】:
我对 Gatsby 很陌生,我想知道我是否可以创建自定义路由(slugs)作为模板。用例是:
- 访问
/articles/name-of-the-article路由 - 使用
name-of-the-articleslug 填充从 API(即 Strapi 无头 CMS)检索到的信息的服务组件Article.js。
【问题讨论】:
标签: reactjs gatsby slug strapi
我对 Gatsby 很陌生,我想知道我是否可以创建自定义路由(slugs)作为模板。用例是:
/articles/name-of-the-article路由name-of-the-article slug 填充从 API(即 Strapi 无头 CMS)检索到的信息的服务组件 Article.js。【问题讨论】:
标签: reactjs gatsby slug strapi
经过一番调查,我发现使用gatsby-plugin-create-client-paths 有一种更简单的方法。
您需要做的就是使用yarn 或npm 安装它,然后在gatsby-config.js 中添加这些:
{
resolve: `gatsby-plugin-create-client-paths`,
options: { prefixes: [`/articles/*`] },
},
这意味着像这样的每个请求 slug:/articles/the-slug 将请求 articles.js 页面并使用 Gatsby 提供的 Link,您可以通过 state 传递 props,如下所示:
<Link to="/articles/the-slug" state={{ slug: "the-slug", ...etc }}>Anchor Text</Link>
这样src/pages/articles.js就变成了以/articles为前缀的slug的模板页面。
【讨论】:
mywebsite.com/articles/some-article 而不是单击Link 组件,那么articles.js 页面组件是否可以在其props 中的某处访问some-article?
是的,你可以。盖茨比有这方面的文档:Creating pages from data programmatically。您需要创建页面 slug:Creating slugs for pages。您需要将gatsby-source-strapi 添加到您的gatsby-config.js。
我对 Strapi 几乎没有经验,因此您需要做一些研究如何使用 Strapi 处理 slug 创建。
示例代码:
gatsby-node.js
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions;
if (node.internal.type === "The Nodes as defined by Strapi") {
const slug = createFilePath({ node, getNode, basePath: "The base paths as defined by Strapi" });
createNodeField({ node, name: "slug", value: slug });
}
};
exports.createPages = async function({ actions, graphql }) {
const { data } = await graphql(`
{
allStrapiArticle {
edges {
node {
id
title
content
}
}
}
}
`)
data.allMarkdownRemark.edges.forEach(edge => {
const slug = edge.node.fields.slug
actions.createPage({
path: slug,
component: require.resolve(`./src/templates/article-template.js`),
context: { slug: slug },
})
})
}
【讨论】: